Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Escaping SSH commands

Tags:

bash

ssh

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 [email protected] 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

like image 230
Dan Avatar asked Jun 02 '13 21:06

Dan


2 Answers

If both sides are using bash, you can escape the arguments using printf '%q ', eg:

ssh [email protected] "$(printf '%q ' mv -v "/home/dan/Downloads/complete/$dir" /home/dan/Downloads/downloaded)"
like image 107
Will Palmer Avatar answered Sep 26 '22 16:09

Will Palmer


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

ssh [email protected] "mv -v /home/dan/Downloads/complete/$dir /home/dan/Downloads/downloaded"
like image 31
fedorqui 'SO stop harming' Avatar answered Sep 23 '22 16:09

fedorqui 'SO stop harming'