【问题标题】:Package tar.gz into a shell script将 tar.gz 打包成一个 shell 脚本
【发布时间】:2015-04-02 16:38:36
【问题描述】:

我想知道如何将 tar.gz 文件打包到 shell 脚本中,就像 idk**.bin 一样。所以我可以在一个 shell 文件而不是 tar.gz 中交付程序

【问题讨论】:

  • 基本概念是编写一个知道如何从文件末尾剪切 tarball 的 shell 脚本,然后将脚本和归档文件放在一起。
  • 在某些设置中,最好在添加之前对 tarball 进行 base64 编码,这样在显示脚本时负载中的不可打印字符就不会导致问题。
  • 我第一次看到具有巨大负载的 .sh 文件时,我感到很惊讶。所以我认为这是一个很有价值的问题,因为我只能想象其他人会同样感到惊讶。

标签: linux shell installation tar


【解决方案1】:

有一个Linux Journal article 详细解释了如何执行此操作,以及用于打包有效负载的代码等。正如 Etan Reisner 在他的评论中所说,提取/安装脚本知道如何切断它的尾巴以获得有效负载这是之前连接的。以下是其工作原理的示例:

#!/bin/bash
# a self-extracting script header

# this can be any preferred output directory
mkdir ./output_dir

# determine the line number of this script where the payload begins
PAYLOAD_LINE=`awk '/^__PAYLOAD_BELOW__/ {print NR + 1; exit 0; }' $0`

# use the tail command and the line number we just determined to skip
# past this leading script code and pipe the payload to tar
tail -n+$PAYLOAD_LINE $0 | tar xzv -C ./output_dir

# now we are free to run code in output_dir or do whatever we want

exit 0

# the 'exit 0' immediately above prevents this line from being executed
__PAYLOAD_BELOW__

注意使用$0 来指代脚本本身。

首先要创建安装程序,您需要连接上面的代码和要安装/交付的压缩包。如果上面的脚本被称为 extract.sh,而有效负载被称为 payload.tar.gz,那么这个命令就可以了:

cat extract.sh payload.tar.gz > run_me.sh

【讨论】:

  • 不完全是书面的,贾希德。您需要在以tail 开头的行上的管道运算符之后修改命令,以调用可以处理您选择的存档的程序。此外,如果该程序无法处理标准输入上的输入,那么您需要将存档写入文件,然后在该文件上调用存档处理程序。
【解决方案2】:

你也可以这样做:

#!/bin/bash
BASEDIR=`dirname "${0}"`
cd "$BASEDIR"

payload=$1
script=$2
tmp=__extract__$RANDOM

[ "$payload" != "" ] || read -e -p "Enter the path of the tar archive: " payload
[ "$script" != "" ] || read -e -p "Enter the name/path of the script: " script

printf "#!/bin/bash
PAYLOAD_LINE=\`awk '/^__PAYLOAD_BELOW__/ {print NR + 1; exit 0; }' \$0\`
tail -n+\$PAYLOAD_LINE \$0 | tar -xvz
#you can add custom installation command here

exit 0
__PAYLOAD_BELOW__\n" > "$tmp"

cat "$tmp" "$payload" > "$script" && rm "$tmp"
chmod +x "$script"

如果你把这个文件保存为t2s,那么你可以这样使用它:

t2s test.tar.gz install.sh

运行install.sh 将提取当前目录中的内容。如果需要,您也可以运行自定义安装脚本。您必须将它们正确添加到 printf 部分。

如果您需要为其他压缩类型(.tar.bz2 等)执行此操作,则需要编辑该部分中的 z 选项:

tail -n+\$PAYLOAD_LINE \$0 | tar xzv
#it's inside a quote and $ needs to be printed, so you will need to use \

例如:

对于 .tar.bz2:

tail -n+\$PAYLOAD_LINE \$0 | tar xjv 
#it's inside a quote and $ needs to be printed, so you will need to use \

对于.tar

tail -n+\$PAYLOAD_LINE \$0 | tar xv 
#it's inside a quote and $ needs to be printed, so you will need to use \

有关此选项的信息,您可以查看 tar 的手册页:

man tar

我已将其设置为 tool 以自动执行这些任务。

【讨论】:

  • 不错的方法,Jahid,都在一个文件中。 +1。但我认为您不需要写着pay=`cat $payload` 的行。首先,$pay 从未使用过,其次,如果$payload 是一个多千兆字节的文件,那么您可能无法将其加载到变量中。 ;)
猜你喜欢
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 2012-01-11
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多