Bash shell 使用变量编写 rsync 脚本
Bash shell scripting rsync with variables
我有以下 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
中的 bugs/insecurities 是正确的。如果有任何其他解决方案可用,那么最好使用它。这里 bash 数组更好。数组答案是更好的答案。
请在
查看答案
要排除的示例列表目录(也是通配符):
#!/bin/sh
export PATH=/usr/local/bin:/usr/bin:/bin
LIST="rootfs usr data data2"
for d in $LIST; do
rsync -az --exclude /$d/ .....
done
我有以下 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
中的 bugs/insecurities 是正确的。如果有任何其他解决方案可用,那么最好使用它。这里 bash 数组更好。数组答案是更好的答案。
请在
要排除的示例列表目录(也是通配符):
#!/bin/sh
export PATH=/usr/local/bin:/usr/bin:/bin
LIST="rootfs usr data data2"
for d in $LIST; do
rsync -az --exclude /$d/ .....
done