在bash脚本中引用rsync的排除问题 [英] Issues quoting exclusions for rsync in bash script

查看:56
本文介绍了在bash脚本中引用rsync的排除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用bash脚本通过rsync同步Web文件夹.我正在使用一系列要排除的文件夹和文件,但在将这些项目转义为排除列表时遇到问题...

I'm using a bash script to sync a web folder using rsync. I'm using an array of folders and files to exclude, and I'm having problems escaping these items for the exclude list...

我的排除列表的定义如下...

my exclude list is defined like so...

SYNC_EXCLUSIONS=(
    '/exclude_folder_1'
    '/exclude_folder_2'
    '.git*'
    '.svn'
)

然后我像这样构建排除字符串...

Then I build my exclusion string like so...

exclusions='';
for e in "${SYNC_EXCLUSIONS[@]}"
do
    exclusions+=" --exclude='$e'";
done

然后最后我执行我的rsync ...

Then finally I execute my rsync...

rsync --recursive --delete $exclusions "$DEPLOYMENT_WORK_DIR/" "$DEPLOYMENT_ROOT/"

如果我回显该命令,则该命令看起来很完美;如果我在提示符下复制并执行了该命令,则它可以正常运行.但是,从脚本运行时,排除项将被忽略.

If I echo the command it looks perfect, and if I copy and execute it at the prompt it works correctly. However when run from the script the exclusions are ignored.

我发现,如果我从每个排除的项目中删除单引号,它将是可行的,就像这样...

I've figured out that it will work if I remove the single quotes from around each excluded item, like so...

exclusions+=" --exclude=$e";

我还是不想这样做,以防万一我需要排除带有空格或特殊字符的文件夹.

I'd prefer to not do that though, just in case I need to exclude folders with spaces or special characters.

在保留被排除项目周围的引号的同时,是否可以通过脚本使它起作用?我已经尝试了各种引号和反斜杠等的组合,但是没有尝试过.

Is there some way I can get this to work from the script while retaining quotes around the excluded items? I've tried all sorts of combinations of quotes and backslashes etc. and nothing I've tried works.

推荐答案

您根本无法为此构建字符串-请参见 BashFAQ#50 ,详细讨论原因.建立一个数组.

You can't build a string for this at all -- see BashFAQ #50 for an extensive discussion of why. Build an array.

exclusions=( )
for e in "${SYNC_EXCLUSIONS[@]}"; do
    exclusions+=( --exclude="$e" )
done

rsync --recursive --delete "${exclusions[@]}" "$DEPLOYMENT_WORK_DIR/" "$DEPLOYMENT_ROOT/"


...嗯,根本无法构建字符串,除非您要使用 eval 执行它.但是,以不容易出现Shell注入漏洞的方式进行操作很重要:


...well, can't build a string at all, unless you're going to execute it with eval. Doing that in a manner that isn't prone to shell injection vulnerabilities takes care, however:

printf -v exclusions_str '--exclude=%q ' "${SYNC_EXCLUSIONS[@]}"
printf -v rsync_cmd 'rsync --recursive --delete %s %q %q' \
  "$exclusions_str" "$DEPLOYMENT_WORK_DIR/" "$DEPLOYMENT_ROOT/"
eval "$rsync_cmd"

这篇关于在bash脚本中引用rsync的排除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆