首页 > 解决方案 > 带有变量的 Bash shell 脚本 rsync

问题描述

我有以下 for 循环,它遍历所有需要复制的给定源。

for i in "${sources[@]}"; do
    exclude="--exclude 'exclude_folder/exclude_file'"

    rsync -az $exclude $i $destination
done

但是,排除选项不起作用。

for i in "${sources[@]}"; do
    exclude="--exclude 'exclude_folder/exclude_file'"

    rsync -az "$exclude" "$i" "$destination"
done

如果我使用上面的代码,rsync 将退出并给出一个未知选项的错误。

如果我只是使用以下代码,它可以工作,但我想为排除选项使用一个变量。

for i in "${sources[@]}"; do
    rsync -az --exclude 'exclude_folder/exclude_file' $i $destination
done

标签: bashubuntursync

解决方案


我会用eval.

你的代码:

for i in "${sources[@]}"; do
    exclude="--exclude 'exclude_folder/exclude_file'"

    rsync -az "$exclude" "$i" "$destination"
done

然后会是(我试图尽可能接近你的逻辑):

for i in "${sources[@]}"; do
    exclude="--exclude 'exclude_folder/exclude_file'"
    rsync_command="rsync -az $exclude $i $destination"

    eval rsync_command
done

eval手册页:

评估

评估几个命令/参数

语法 eval [参数]

参数连接在一起形成一个命令,然后读取并执行该命令,其退出状态作为 eval 的退出状态返回。如果没有参数或只有空参数,则返回状态为零。

eval 是一个 POSIX `special' 内置

编辑

Gordon Davisson 对eval. 如果有任何其他解决方案可用,那么最好使用它。这里的 bash 数组更好。数组答案是优越的答案。

请参阅Bash 的答案:需要帮助将 aa 变量传递给 rsync


推荐阅读