0

I can run the followind loop locally

for i in A B C; do mycommand $i; done

Now I am trying to send it over ssh

The following version

ssh myhost for i in A B C; do mycommand $i; done

The following version

ssh myhost "for i in A B C; do mycommand $i; done"

also fails, because it wants i varibale locally.

How to handle?


Is there any general approach, for example, what if mycommand is another ssh?

ssh myhost 'for i in hos1 host2 host3; do ssh "$i" ... another for expression
Dims
  • 3,255

1 Answers1

6

Just use single quote:

ssh myhost 'for i in A B C; do mycommand "$i"; done'

That will use the $i as literal characters to the ssh command instead of having the local shell substitute them. In general, you'll also want to double-quote the expansion to prevent issues with issues with word splitting, though it's not strictly necessary with the values here.

See:

ilkkachu
  • 138,973
Lie Ryan
  • 1,228
  • Hm, can't figure general approach, this is ad-hoc. – Dims Feb 21 '23 at 14:12
  • @Dims: the shell normally expands $whatever to replace it with the variable content before running the command. It also does so inside of double quotes like so: echo "$PWD". Here, you want the shell to treat $ as a literal symbol, and not expand it. Use single quotes like echo '$PWD' (try both commands!) or escape the $ character: echo \$PWD. – MayeulC Feb 21 '23 at 15:37