標籤:abs bash-shell advanced
書上的指令碼比較多 記錄比較有用的指令碼
更好的方式檢查命令列參數是否為數字
40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format).41 #42 # case "$1" in43 # "" ) lines=50;;44 # *[!0-9]*) echo "Usage: `basename $0` lines-to-cleanup";45 # exit $E_WRONGARGS;;46 # * ) lines=$1;;47 # esac
更好的方式檢查命令列參數數量是否正確
1 E_WRONG_ARGS=852 script_parameters="-a -h -m -z"3 # -a = all, -h = help, etc.45 if [ $# -ne $Number_of_expected_args ]6 then7 echo "Usage: `basename $0` $script_parameters"8 # `basename $0` is the script‘s filename.9 exit $E_WRONG_ARGS10 fi
更好的方式檢查是否在正確的目錄
63 # cd /var/log || {64 # echo "Cannot change to necessary directory." >&265 # exit $E_XCD;66 # }
備份來源目錄的檔案並且在目標目錄解壓
(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)一個更加有效指令碼是cd source/directory# tar cf - . | (cd ../dest/directory; tar xpvf -)或cp -a /source/directory/* /dest/directory# cp -a /source/directory/* /source/directory/.[^.]* /dest/directory #這個複製來源目錄的隱藏檔案
備份最近24小時內改變的檔案
#!/bin/bashBACKUPFILE=backup-$(date +%m-%d-%Y)archive=${1:-$BACKUPFILE}# 如果在命令列中沒有指定參數,就是用如下的格式# it will default to "backup-MM-DD-YYYY.tar.gz."tar cvf - `find . -mtime -1 -type f -print` > $archive.targzip $archive.tarecho "Directory $PWD backed up in archive file \"$archive.tar.gz\"."
如果檔案太多或者檔案名稱有空白字元,上面的指令碼可能出錯
更好的備份方案 tar -r 追加到歸檔檔案
# -------------------------------------------------------------------# find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"或# find . -mtime -1 -type f -exec tar rvf "$archive.tar" ‘{}‘ \;exit 0
擷取命令列參數的最後一個參數
args=$# # Number of args passed.lastarg=${!args}# Note: This is an *indirect reference* to $args ...# Or: lastarg=${!#}
${file#*/} :拿掉第一條 / 及其左邊的字串:dir1/dir2/dir3/my.file.txt
${file##*/} :拿掉最後一條 / 及其左邊的字串:my.file.txt
${file#*.} :拿掉第一個 . 及其左邊的字串:file.txt
${file##*.} :拿掉最後一個 . 及其左邊的字串:txt
${file%/*} :拿掉最後條 / 及其右邊的字串:/dir1/dir2/dir3
${file%%/*} :拿掉第一條 / 及其右邊的字串:(空值)
${file%.*} :拿掉最後一個 . 及其右邊的字串:/dir1/dir2/dir3/my.file
${file%%.*} :拿掉第一個 . 及其右邊的字串:/dir1/dir2/dir3/my
本文出自 “Linux is belong to you” 部落格,請務必保留此出處http://jwh5566.blog.51cto.com/7394620/1657455
Advanced Bash-Shell Guide(Version 10) 學習筆記三