Advanced Bash-Shell Guide(Version 10) 學習筆記三

來源:互聯網
上載者:User

標籤: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) 學習筆記三

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.