bash - 带有变量的 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
解决方案
我会用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 数组更好。数组答案是优越的答案。
推荐阅读
- datatable - Yii2 Basic:index.php 中的分页代码在哪里?
- c++ - 如何通过 CNG 使用 RSA 私钥签名
- spring - spring rest doc - 服务层模拟
- gradle - 如何在单个构建中将一个 Gradle 子项目生成的 jar 复制到另一个中
- asp.net - Href to go to another page and load ajax on that page
- node.js - Sequelize 不记录 sql 查询
- java - 如何为所有 OneToMany 实体设置值?
- dialogflow-es - 如何在 Fulfillment 中使用列表参数
- r - 给定一个列名向量,如何检查它们是否都是数字?
- typescript - 为了保证类型安全,“as const”断言是这里唯一的解决方案吗?