bash:rsync 与选项作为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19219774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:12:14  来源:igfitidea点击:

bash: rsync with options as variable

bashsshrsync

提问by Piotr

I am writing bash script, which in some part will rsync files over ssh. Unfortunately I am facing problem with keeping rsync options as variable. Please take a look below:

我正在编写 bash 脚本,它在某些部分将通过 ssh rsync 文件。不幸的是,我在将 rsync 选项保持为变量时遇到了问题。请看下面:

    # variables
    directory="/etc"
    backupDirectory="/backup"
    incrementalBackup="/incremental"
    options="-a -e 'ssh -p 10022' -b --backup-dir=$incrementalBackup --delete"
    # rsync
    rsync $options user@server:$directory $backupDirectory

Unfortunately above script fails with rsync error:

不幸的是,上面的脚本因 rsync 错误而失败:

    Unexpected remote arg: user@server:/etc
    rsync error: syntax or usage error (code 1) at main.c(1201) [sender=3.0.6]

What I saw during script debugging is the fact, that ssh options ('ssh -p 10022') are treated as rsync options. The question is how to pass correctly those additional ssh settings into rsync? Thanks in advance for a tip.

我在脚本调试期间看到的事实是,ssh 选项('ssh -p 10022')被视为 rsync 选项。问题是如何将这些额外的 ssh 设置正确传递到 rsync 中?提前感谢您的提示。

采纳答案by devnull

Use eval. Try:

使用eval. 尝试:

eval rsync $options user@server:$directory $backupDirectory

回答by chepner

Use an array; it's why they were added to bash:

使用数组;这就是为什么它们被添加到bash

# variables
directory="/etc"
backupDirectory="/backup"
incrementalBackup="/incremental"
options=(-a -e 'ssh -p 10022' -b --backup-dir="$incrementalBackup" --delete)
# rsync
rsync "${options[@]}" user@server:"$directory" "$backupDirectory"

evalis not a safe option to use; it isn't limited to just evaluating the quotations you intend it to, but will evaluate anycode. It might work for your current situation, but changes to the value of optionsmight bring unforeseen consequences, and it's generally a bad idea to get into the habit of using evalwhen it isn't necessary.

eval不是一个安全的使用选择;它不仅限于评估您想要的引用,而且会评估任何代码。它可能适用于您当前的情况,但更改 的值options可能会带来不可预见的后果,并且养成在eval不必要时使用的习惯通常是一个坏主意。