将 tar.gz 打包成 shell 脚本

Package tar.gz into a shell script

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

中交付程序

有一个 Linux Journal article 详细解释了如何执行此操作,以及打包有效载荷的代码等。正如 Etan Reisner 在他的评论中所说,extraction/installation 脚本知道如何削减它的tail off 以获得先前连接的有效负载。这是一个如何工作的例子:

#!/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; }' [=10=]`

# 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 [=10=] | 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__

请注意使用 [=12=] 来引用脚本本身。

首先要创建安装程序,您需要将上面的代码和您想要的 tarball 连接起来 install/deliver。如果上面的脚本被称为 extract.sh,有效载荷被称为 payload.tar.gz,那么这个命令就可以达到目的:

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

你也可以这样做:

#!/bin/bash
BASEDIR=`dirname "[=10=]"`
cd "$BASEDIR"

payload=
script=
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

I have made it into a tool to automate these tasks.