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,181
  • 9
  • 49
  • 107
  • [Quoting in ssh $host $FOO and ssh $host "sudo su user -c $FOO" type constructs](https://unix.stackexchange.com/q/4770/170373) -- better yet, don't pass the commands over the command line so you avoid the quoting hell completely – ilkkachu Feb 21 '23 at 14:18
  • For Bash, but gives some insight: [How can I single-quote or escape the whole command line in Bash conveniently?](https://superuser.com/q/1531395/432690) A general approach can be summarized as (from [this answer](https://superuser.com/a/1534401/432690)): "To be in control of what the remote shell will get as `$command_line_built_by_ssh`, you need to understand, predict and mastermind the parsing and interpreting that happens before. You need to craft your local command, so after the local shell and `ssh` digest it, it becomes the exact `$command_line…` you want to execute on the remote side." – Kamil Maciorowski Feb 21 '23 at 14:31

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
  • 133,243
  • 15
  • 236
  • 397
Lie Ryan
  • 1,208
  • 7
  • 12
  • 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