簡體   English   中英

用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"'

但在腳本的最后一個命令opt1opt2由沒有他們的值替代'' ,但各部分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定義放在excllogfile定義之后,因此可以在定義的行中對其進行擴展。 但我不想這樣做,因為在未來,我想有些循環添加到上面的腳本並以這種方式我不得不重新定義opt3每次excllogfile的變化。

您應該使用數組存儲程序參數。 使用它們來設置opt3的值之前,還需要定義logfileexcl

#!/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM