![](/img/trans.png)
[英]Replacing 'source file' with its content, and expanding variables, in bash
[英]Replacing a variable by its exact value (not expanding) in bash
我編寫了如下腳本:
#!/bin/bash
opt1='-vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links'
opt2="--progress --exclude-from=$HOME/exrsync"
opt3='--exclude-from="$excl" --log-file="$logfile"'
src="$HOME"
dest="/My Backup/home/"
excl="$HOME/exrsync-gh"
logfile="rsync_home.log"
rm -f "$logfile"
rsync ${opt1} ${opt2} ${opt3} "$src" "$dest"
基於bash -x myscript.sh
輸出:
opt1
沒有要擴展的內容,即:
+ opt1='-vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links'
opt2
在定義的行上展開,即:
+ opt2='--progress --exclude-from=/home/username/exrsync'
並且opt3
不在其定義的行中展開,即:
+ opt3='--exclude-from="$excl" --log-file="$logfile"'
但在腳本的最后一個命令opt1
和opt2
由沒有他們的值替代''
,但各部分opt3
是推桿單引號,即內:
+ rsync -vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links --progress --exclude-from=/home/me/backup/rsync/exrsync
'--exclude-from="$excl"' '--log-file="$logfile"'
+ rsync -vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links --progress --exclude-from=/home/me/backup/rsync/exrsync
'--exclude-from="$excl"' '--log-file="$logfile"'
/home/me '/My Backup/home/'
顯然,以上命令將返回錯誤:
rsync: failed to open exclude file "$excl": No such file or directory (2)
rsync error: error in file IO (code 11) at exclude.c(1179) [client=3.1.0]
我需要opt3
opt3,例如opt1
被替換。 因此,最后一條命令將如下所示:
+ rsync -vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links --progress --exclude-from=/home/me/backup/rsync/exrsync
--exclude-from=/home/me/exrsync-gh --log-file=rsync_home.log
/home/me '/My Backup/home/'
注意:
一種解決方案是將opt3
定義放在excl
和logfile
定義之后,因此可以在定義的行中對其進行擴展。 但我不想這樣做,因為在未來,我想有些循環添加到上面的腳本並以這種方式我不得不重新定義opt3
每次excl
或logfile
的變化。
您應該使用數組存儲程序參數。 在使用它們來設置opt3
的值之前,還需要定義logfile
和excl
。
#!/bin/bash
src="$HOME"
dest="/My Backup/home/"
excl="$HOME/exrsync-gh"
logfile="rsync_home.log"
opt1=(-vvaumrhhhsq --info=name1 --delete --modify-window=2 --safe-links)
opt2=(--progress --exclude-from=$HOME/exrsync)
opt3=(--exclude-from="$excl" --log-file="$logfile")
rm -f "$logfile"
rsync "${opt1[@]}" "${opt2[@]}" "${opt3[@]}" "$src" "$dest"
您可以做的一件事是將rsync
命令包裝在一個函數中,該函數將帶有兩個參數, excl
的值和logfile
的值。
syncer () {
excl=$1
logfile=$2
shift 2
options=( --vvaumrhhhsq
--info=name1
--delete
# etc
)
rsync "${options[@]}" --exclude-from="$excl" --log-file="$logfile" "$@"
}
syncer "$excl" "$logfile" "$src" "$dest"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.