Executing local script/command on remote server

I have a command that I want to run on machine B from machine A. If I run the command on machine B locally, it works fine.

Here is the command:

 for n in `find /data1/ -name 'ini*.ext'` ; do  echo cp $n "`dirname $n `/` basename $n 
    .ext`"; done

From machine A, I issue this command

ssh user@machineB  for n in `find /data1/ -name 'ini*jsem'` ; do  echo cp $n "`dirname $n `/` basename $n .jsem`"; done

But I get error

`syntax error near unexpected token do`

What is wrong? I think it has something to do with double quotes, single quotes, semi colon because executing command

 `ssh user@machineB ls`

works fine. So not issue of authentication or something else.

Thanks

script_to_run:

for n in $(find /data1 -name 'ini*.ext'); do  
     echo cp $n "${n}.ext"
done

Invoking the script:

ssh user@machineB "bash -s" < script_to_run
3 Likes

Thank you, that worked perfectly

What you have here is the shell on machine A interpreting the command line rather than just passing it over to machine B. It seems the semi colon as part of the command to machine A.

Try adding single quotes around the entire command you wish to pass, so probably before the for and after the done although you will have to then consider if you need to escape the single quotes you have in the string you are passing. You might end up with:-

ssh user@machineB 'for n in `find /data1/ -name \'ini*jsem\'` ; do  echo cp $n "`dirname $n `/` basename $n .jsem`"; done'

Have a play with simpler code to work out what gets passed and how on your systems.

I'm not too sure if ; done is valid either. Does this exact command work when run directly on machine B? If so, then I'm obviously mistaken. So many coding styles.......

I hope that this helps,

Robin
Liverpool/Blackburn, UK