gpt4 book ai didi

带有变量的 Bash shell 脚本 rsync

转载 作者:行者123 更新时间:2023-12-04 18:50:45 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Bash: need help passing a a variable to rsync

(3 个回答)


4年前关闭。




我有以下 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

最佳答案

我会使用 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

Evaluate several commands/arguments

Syntax eval [arguments]

The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

eval is a POSIX `special' builtin



编辑

Gordon Davisson 关于 eval 中的错误/不安全感是正确的.如果有任何其他解决方案可用,那么最好使用它。这里的 bash 数组更好。数组答案是优越的答案。

请在 上查看答案Bash: need help passing a a variable to rsync

关于带有变量的 Bash shell 脚本 rsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com