bash - 分配多行 shell 变量,包括带有嵌入空格和引号的文件作为 rsync 命令的参数
问题描述
SO上的所有其他解决方案都适用于echo
类似的命令。但是,我正在尝试将一长串参数(分成多行)分配给单个变量,该变量将扩展为 rsync 命令的多个参数。关于 rsync 命令(或 bash 的空格标记)的某些内容不适用于大多数推荐的解决方案。
SYNC_OPTIONS="-a --progress --delete --delete-before --delete-excluded"
SYNC_EXCLUDE="
--exclude='some/dir/with spaces/requiring quoting'
--exclude='another/dir/with spaces'
--exclude='blah blah/blah'
"
echo rsync ${SYNC_OPTIONS} ${SYNC_EXCLUDE} /src/ /dst/
set -x
rsync ${SYNC_OPTIONS} ${SYNC_EXCLUDE} /src/ /dst/
set +x
产生:
$ echo rsync ${SYNC_OPTIONS} ${SYNC_EXCLUDE} /src/ /dst/
rsync -a --progress --delete --delete-before --delete-excluded --exclude='some/dir/with spaces/requiring quoting' --exclude='another/dir/with spaces' --exclude='blah blah/blah' /src/ /dst/
$ set -x
$ rsync ${SYNC_OPTIONS} ${SYNC_EXCLUDE} /src/ /dst/
+ rsync -a --progress --delete --delete-before --delete-excluded '--exclude='\''some/dir/with' spaces/requiring 'quoting'\''' '--exclude='\''another/dir/with' 'spaces'\''' '--exclude='\''blah' 'blah/blah'\''' /src/ /dst/
rsync: change_dir "/spaces" failed: No such file or directory (2)
rsync: link_stat "/quoting'" failed: No such file or directory (2)
rsync: link_stat "/spaces'" failed: No such file or directory (2)
rsync: change_dir "/blah" failed: No such file or directory (2)
跟踪输出和 rsync 错误消息都表明存在一些额外的、不需要的标记化级别,这会破坏 rsync 命令中变量的使用。但是,该echo
命令的输出看起来是正确的。
如何定义一个多行变量,它将用作 rsync 命令的参数,其中参数包含带空格的引用文件路径?具体来说,我对SYNC_EXCLUDE
变量的上述情况感兴趣。
解决方案
终于在这里找到了嵌入冗长但很好的答案的答案。就我而言,我将变量转换为字符串数组,而不是单个长字符串,如下所示:
SYNC_OPTIONS="-a --progress --delete --delete-before --delete-excluded"
SYNC_EXCLUDE=(
--exclude='some/dir/with spaces/requiring quoting'
--exclude='another/dir/with spaces'
--exclude='blah blah/blah'
)
echo rsync ${SYNC_OPTIONS} "${SYNC_EXCLUDE[@]}" /src/ /dst/
set -x
rsync ${SYNC_OPTIONS} "${SYNC_EXCLUDE[@]}" /src/ /dst/
set +x
推荐阅读
- python - 如何在 Spark 的 Logistic 回归分类器中将多个列作为特征传递?
- python - Django:如何预取模型实例的相关信息。也许通过包装查询集?
- oauth-2.0 - oidc 中多个提供商的相同重定向 uri
- bash - 用 bash 读取 .env(带空格的变量)
- javascript - 如何在单击按钮时自行关闭网页
- ios - 如何识别用户在 iOS 中所做的最后一项活动
- angular - 如何使用 httpclient 发布请求解决 Angular 应用程序中的 Access-Control-Allow-Origin?
- angularjs - 如何为离子应用程序创建本地通知?
- api - 设备:(70:18)类型错误:未定义不是对象(评估“articles.map”)
- php - mysql select中的if子句