将tar.gz打包成shell脚本

时间:2015-04-02 16:38:37

标签: linux shell installation installer tar

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

中提供程序

2 个答案:

答案 0 :(得分:5)

有一个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来引用脚本本身。

要首先创建安装程序,您需要连接上面的代码和要安装/交付的tarball。如果上面的脚本名为extract.sh,并且有效负载名为payload.tar.gz,则此命令可以解决问题:

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

答案 1 :(得分:1)

你也可以这样做:

#!/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以自动执行这些任务。