![](/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.