Bash - Executing SSH Commands

I have a set of scripts that I use to upload 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 may be “This is a file”, which works fine.

I have a problem with special characters, for example:

  • "This is (a) a file"
  • This is a file and more.

have a tendency 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 figure out how to avoid this, as the variable gets evaluated and the command gets the escaped label. I tried various combinations of escape characters, letter quotes, regular quotes, etc.

+6
source share
4 answers

If both sides use bash, you can avoid arguments with printf '%q ' , for example:

 ssh dan@172.19.1.15 "$(printf '%q ' mv -v "/home/dan/Downloads/complete/$dir" /home/dan/Downloads/downloaded)" 
+17
source

You need to quote the entire ssh user@host "command" expression:

 ssh dan@172.19.1.15 "mv -v /home/dan/Downloads/complete/$dir /home/dan/Downloads/downloaded" 
+1
source

I am confused because your code, as written, works for me:

 > 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 

For debugging, use set -vx at the top of the script to find out what happens.

0
source

Whether Palmer’s suggestion to use printf fine, but I think it makes sense to put literals in printf format.

Thus, single-user commands with multiple commands are more intuitive to write:

 ssh user@host "$(printf 'mkdir -p -- %q && cd -- "$_" && tar -zx' "$DIR")" 
0
source

Source: https://habr.com/ru/post/946364/


All Articles