【问题标题】:Bash unintentionally splitting commandBash无意中拆分命令
【发布时间】:2018-10-03 06:32:07
【问题描述】:

目前我有一个 rsync 命令,由于网络状况不佳,每约 15 分钟失败一次。我编写了一个脚本来重新运行 rsync,但是该脚本无法按预期工作,因为 bash 无意中破坏了我传入的命令:

$ cat exit-trap.sh
#!/bin/bash
count=1

while :
do
        echo ==============
        echo Run \#$count
        $@
        if [[ $? -eq 0 ]] ; then
                exit
        fi
        echo Run \#$count failed
        let count++
        sleep 15
done

$ ./exit-trap.sh rsync --output-format="@ %i  %n%L" source::dir target
==============
Run #1
Unexpected remote arg: source::dir
rsync error: syntax or usage error (code 1) at main.c(1348) [sender=3.1.1]

看了一会儿后,我猜 rsync 在 argv 中收到的是 `["rsync", "--output-format=@", "%i", "%n%L", "source::dir “, “目标”]。输出格式似乎无意中被拆分为单独的部分,从而导致语法错误。有没有办法解决这个问题?

PS:到目前为止,我还尝试过sh -c $@sh -c \"$@\"

  • ./exit-trap.sh rsync --output-format=\"@ %i %n%L\" source::dir target

  • ./exit-trap.sh rsync --output-format=\\\"@ %i %n%L\\\" source::dir target

  • ./exit-trap.sh "rsync --output-format=\"@ %i %n%L\" source::dir target"

这些都不起作用。

【问题讨论】:

    标签: bash shell command-line-arguments


    【解决方案1】:

    您需要使用"$@",如此处所述https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters

    ($@) 扩展为位置参数,从一开始。当扩展出现在双引号内时,每个参数都扩展为一个单独的单词。也就是说,“$@”等价于“$1”“$2”……

    【讨论】:

    • 工作就像一个魅力!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2013-05-19
    相关资源
    最近更新 更多