繁体   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