Linux 下自解压文件的制作

这个方法的灵感来自于 alipay 的安全控件安装,所以先感谢 alipay。

下面是经过我自己修改的自解压 shell 代码(嵌入式板子上是busybox提供的sh)

#!/bin/sh
#
# Thanks to Alipay Corporation
#
# Author: Zhenxing Luo
# Date:   2015/12/03
# Support: If you have any question, please feel free to call me
# MOB:15257413812
# 

rmOld()
{
    rm -rf /opt/Qtopia/apps/*
    rm -rf /usr/local/Trolltech/QtEmbedded-4.8.5-arm/lib/fonts/*

    echo "Ready! Begin updating..."
    return 0
}

checkVersion()
{
    board=`uname -r`

    if [ $board != "3.6.0-FriendlyARM" ]
    then
        echo "This file is for Mini2451-1307 only!"
        exit 1
    fi
    return 0
}

main()
{
    checkVersion

    rmOld

    ARCHIVE=`awk '/^__ARCHIVE_BELOW__/ {print NR + 1; exit 0; }' "$0"`
    tail -n+$ARCHIVE "$0" | tar xzvm -C /> /dev/null 2>&1 3>&1
    if [ $? -ne 0 ]
    then
        echo "Failed! Don't do any edit to this file!"
        exit 1
    fi
    echo "Done! Have a nice day :)"
    exit 0
}

main

#This line must be the last line of the file
__ARCHIVE_BELOW__


--- the tar.gz here ---

其中,main()里面做了自解压的事,主要步骤是:

1. 用 awk 在本文件中( $0 是程序的第一个参数,即自己的文件名 )里查找 “__ARCHIVE_BELOW__” 这一句, 返回行号。

2. 使用 tail 截取本文件从"行号 +1" 之后的内容,并将其通过管道传给 tar,由 tar 负责解压。

另外,因为这个自解压程序是用 shell 写的,所以,在解压之前,还可以做一些其他的事,比如,我上面的检查系统版本和删除旧文件。所以,这种方法是拿来做升级包和安装包的不二之选。

 

至于用法,需要的人应该一眼就能看出该怎么用 :)

====================================================

接上面,二机制文件在拷贝和传输过程中,还是有可能被损坏的;或者杀毒软件会被奇怪的二进制代码认定为某种威胁。

然后,就有了先对二进制文件进行编码的想法,用 base64 编码将二机制文件转化为文本文件再传输。

下面是这个思路的一种实现。

#!/usr/bin/env bash

function mkpackage(){
    target_dir=$1
    felow_install_shell_command_file=$2
    
    tar -zcf ._test_dir.tar.gz $target_dir
    echo "tar is done!" 

    base64 ._test_dir.tar.gz >._base64
    rm ._test_dir.tar.gz
    echo "base64 coding is done!" 
    
    echo "#!/usr/bin/env bash" >install.sh
    echo "" >>install.sh

    echo "test_base64=\\" >>install.sh
    while IFS='' read -r line || [[ -n "$line" ]]; do
        echo "$line\\" >>install.sh
    done <./._base64 
    rm ._base64
    
    echo "" >>install.sh
    echo "" >>install.sh
    
    echo 'printf $test_base64|base64 -d >._temp.tar.gz;'>>install.sh
    echo 'tar zxf ._temp.tar.gz' >> install.sh
    echo 'rm ._temp.tar.gz' >>install.sh

    echo "install.sh is ready!"

    if [[ -e $fellow_install_shell_command_file ]]; then
        cat $fellow_install_shell_command_file >>install.sh
    fi
    
    chmod +x install.sh
}
function usage(){
   echo "usage:"
   echo "    $1 test_dir [the_command.sh]"
}

if [[ $# != 0 ]]
then
   mkpackage $1 $2
else
   usage $0
fi

 

该方法来自于(好像是编辑器问题,博主给的代码有问题,上面贴的是我修正的代码):http://www.jianshu.com/p/0cc02fa6eb87

posted @ 2015-12-03 15:56  Biiigfish  阅读(2540)  评论(0编辑  收藏  举报