Bash 无意中拆分命令
Bash unintentionally splitting command
目前我有一个 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"、"target"]。输出格式似乎无意中被分割成单独的部分,导致语法错误。有办法解决这个问题吗?
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"
None 个作品。
您需要按照此处所述使用 "$@"
https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters:
($@) Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "" "" ….
目前我有一个 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"、"target"]。输出格式似乎无意中被分割成单独的部分,导致语法错误。有办法解决这个问题吗?
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"
None 个作品。
您需要按照此处所述使用 "$@"
https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#Special-Parameters:
($@) Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "" "" ….