標籤:
有時候給別人分享一個工具的時候,同時需要提供的檔案比較多;
如果分享一個壓縮包還得教會對方如何解壓、執行哪個指令碼,感覺需要傳輸的內容多了就不方便;
把幾個Shell指令碼和檔案打包成一個“單獨的可執行檔”,對方接收到這個檔案,只需要執行一下這個檔案,就可以實現解壓、執行對應指令碼了,相對比較方便;
#!/bin/bash - #===============================================================================## FILE: shell_pack.sh# # USAGE: ./shell_pack.sh # # DESCRIPTION: # # OPTIONS: ---# REQUIREMENTS: ---# BUGS: ---# NOTES: ---# AUTHOR: lwq (28120), [email protected]# ORGANIZATION: # CREATED: 04/22/2015 02:38:01 PM CST# REVISION: ---#===============================================================================#=== FUNCTION ================================================================# NAME: usage# DESCRIPTION: Display usage information.#===============================================================================function usage (){ cat <<- EOT Usage : $0 -p package -s script file1 file2 file3 .. Options: -h|help Display this message -p|package The output package name -s|script The script will run when unpack package Other The all files what you want to packEOT} # ---------- end of function usage ----------#-----------------------------------------------------------------------# Handle command line arguments#-----------------------------------------------------------------------while getopts ":hp:s:" optdo case $opt in h|help ) usage; exit 0 ;; p|package ) package_name=$OPTARG ;; s|script ) install_script=$OPTARG ;; \? ) echo -e "\n Option does not exist : $OPTARG\n" usage; exit 1 ;; esac # --- end of case ---doneshift $(($OPTIND-1))if [[ -z $package_name ]]; then echo "package_name can‘t not be empty" usage exitfiif [[ -z $package_name ]]; then echo "install_script can‘t not be empty" usage exitfifiles=[email protected]generate_wrapper_script(){ local install_script=$1 local wrapper_script=$2 cat <<-‘EOT‘ >$wrapper_script#!/bin/shecho "begin ..."unpackdir=/tmp/$(basename $0)_unpackrm -rf $unpackdir 2>/dev/nullmkdir -p $unpackdirecho "unpacking ..."sed ‘1, /^#__SCRIPTEND__/d‘ $0 | tar zxf - -C $unpackdirif [ $? -ne 0 ]; then echo "unpack package failed." exit 1fiecho ""echo "installing ..."cd $unpackdirEOT cat <<-EOR >>$wrapper_scriptchmod +x $install_script./$install_scriptEOR cat <<-‘EOE‘ >>$wrapper_scriptif [ $? -ne 0 ]; then echo "install failed." exit 2elif [[ -d $unpackdir ]]; then rm -rf $unpackdirfiecho "install ok, enjoy!"exit 0#__SCRIPTEND__EOE}tarfile=package_content_$$.tgzwrapfile=wrap_$$.shecho -e "start packing ..\n"tar zcvf $tarfile $files $install_scriptgenerate_wrapper_script $install_script $wrapfilecat $wrapfile $tarfile > $package_namechmod +x $package_nameecho -e "\noutput: $package_name\n"rm -f $tarfilerm -f $wrapfile
檔案內容儲存到 shell_pack.sh,使用方法舉例:
./shell_pack.sh -p logcat_install -s logcat_install.sh logcat_all.sh logcat_wrapper.sh vmstat2
將產生可執行檔“logcat_install”,執行logcat_install時,會解壓自身檔案內的tar.gz檔案,並執行關鍵的指令碼 logcat_install.sh
〖Linux〗簡單的將Shell和一些檔案打包成一個單獨的“可執行檔”