首页 > 解决方案 > 分配多行 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变量的上述情况感兴趣。

标签: bashshellvariablesargumentsquoting

解决方案


终于在这里找到了嵌入冗长但很好的答案的答案。就我而言,我将变量转换为字符串数组,而不是单个长字符串,如下所示:

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

推荐阅读