7

I have a set of scripts that I use to download files via FTP and then delete them from the server.

It works as follows:

for dir in `ls /volume1/auto_downloads/sync-complete`
do
if [ "x$dir" != *"x"* ]
then
echo "DIR: $dir"

echo "Moving out of complete"
        # Soft delete from server so they don't get downloaded again
        ssh dan@172.19.1.15 mv -v "'/home/dan/Downloads/complete/$dir'" /home/dan/Downloads/downloaded

Now $dir could be "This is a file" which works fine.

The problem I'm having is with special characters eg:

  • "This is (a) file"
  • This is a file & stuff"

tend to error:

bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `mv -v '/home/dan/Downloads/complete/This is (a) file' /home/dan/Downloads/downloaded'

I can't work out how to escape it so both the variable gets evaluated and the command gets escaped properly. I've tried various combinations of escape characters, literal quotes, normal quotes, etc

4

5 回答 5

21

如果双方都使用 bash,您可以使用 转义参数printf '%q ',例如:

ssh dan@172.19.1.15 "$(printf '%q ' mv -v "/home/dan/Downloads/complete/$dir" /home/dan/Downloads/downloaded)"
于 2013-06-02T21:39:36.253 回答
2

您需要引用整个表达式ssh user@host "command"

ssh dan@172.19.1.15 "mv -v /home/dan/Downloads/complete/$dir /home/dan/Downloads/downloaded"
于 2013-06-02T21:33:52.417 回答
0

我很困惑,因为您编写的代码对我有用:

> dir='foo & bar (and) baz'
> ssh host  mv -v "'/home/dan/Downloads/complete/$dir'" /home/dan/Downloads/downloaded
mv: cannot stat `/home/dan/Downloads/complete/foo & bar (and) baz': No such file or directory

对于调试,set -vx请在脚本顶部使用以查看发生了什么。

于 2013-06-02T21:46:01.777 回答
0

Will Palmer 的 using 建议printf很棒,但我认为将文字部分放在printf' 格式中更有意义。

这样,多命令单行代码写起来更直观:

ssh user@host "$(printf 'mkdir -p -- %q && cd -- "$_" && tar -zx' "$DIR")"
于 2017-03-17T01:47:23.647 回答
0

shlex.quote(s)一个可以使用python

返回字符串 s 的 shell 转义版本

文档

于 2020-06-15T15:23:52.660 回答