溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Advanced Bash-Shell Guide(Version 10) 學(xué)習(xí)筆記三

發(fā)布時(shí)間:2020-06-15 12:17:06 來源:網(wǎng)絡(luò) 閱讀:551 作者:蔣文華 欄目:大數(shù)據(jù)

書上的腳本比較多 記錄比較有用的腳本

更好的方式檢查命令行參數(shù)是否為數(shù)字

40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format).
41 #
42 # case "$1" in
43 # "" ) lines=50;;
44 # *[!0-9]*) echo "Usage: `basename $0` lines-to-cleanup";
45 # exit $E_WRONGARGS;;
46 # * ) lines=$1;;
47 # esac


更好的方式檢查命令行參數(shù)數(shù)量是否正確

1 E_WRONG_ARGS=85
2 script_parameters="-a -h -m -z"
3 # -a = all, -h = help, etc.
4
5 if [ $# -ne $Number_of_expected_args ]
6 then
7 echo "Usage: `basename $0` $script_parameters"
8 # `basename $0` is the script's filename.
9 exit $E_WRONG_ARGS
10 fi


更好的方式檢查是否在正確的目錄

63 # cd /var/log || {
64 # echo "Cannot change to necessary directory." >&2
65 # exit $E_XCD;
66 # }


備份源目錄的文件并且在目標(biāo)目錄解壓

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)
一個(gè)更加有效的腳本是
cd source/directory
# tar cf - . | (cd ../dest/directory; tar xpvf -)
或
cp -a /source/directory/* /dest/directory
# cp -a /source/directory/* /source/directory/.[^.]* /dest/directory 
#這個(gè)復(fù)制源目錄的隱藏文件


備份最近24小時(shí)內(nèi)改變的文件

#!/bin/bash

BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}
# 如果在命令行中沒有指定參數(shù),就是用如下的格式
# it will default to "backup-MM-DD-YYYY.tar.gz."

tar cvf - `find . -mtime -1 -type f -print` > $archive.tar
gzip $archive.tar
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."


如果文件太多或者文件名有空白字符,上面的腳本可能出錯(cuò)

更好的備份方案   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


獲取命令行參數(shù)的最后一個(gè)參數(shù)

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#*.} :拿掉第一個(gè) . 及其左邊的字符串:file.txt
${file##*.} :拿掉最后一個(gè) . 及其左邊的字符串:txt
${file%/*} :拿掉最后條 / 及其右邊的字符串:/dir1/dir2/dir3
${file%%/*} :拿掉第一條 / 及其右邊的字符串:(空值)
${file%.*} :拿掉最后一個(gè) . 及其右邊的字符串:/dir1/dir2/dir3/my.file
${file%%.*} :拿掉第一個(gè) . 及其右邊的字符串:/dir1/dir2/dir3/my




向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI