Richard
Richard

Reputation: 15602

How to pass local variable to remote ssh commands?

I need to execute multiple commands on remote machine, and use ssh to do so,

ssh root@remote_server 'cd /root/dir; ./run.sh'

In the script, I want to pass a local variable $argument when executing run.sh, like

ssh root@remote_server 'cd /root/dir; ./run.sh $argument'

It does not work, since in single quote $argument is not interpreted the expected way.

Edit: I know double quote may be used, but is there any side effects on that?

Upvotes: 2

Views: 6653

Answers (2)

Zim
Zim

Reputation: 515

You can safely use double quotes here.

ssh root@remote_server "cd /root/dir; ./run.sh $argument"

This will expand the $argument variable. There is nothing else present that poses any risk.

If you have a case where you do need to expand some variables, but not others, you can escape them with backslashes.

$ argument='-V'
$ echo "the variable \$argument is $argument"

would display

the variable $argument is -V

You can always test with double quotes to discover any hidden problems that might catch you by surprise. You can always safely test with echo.

Additionally, another way to run multiple commands is to redirect stdin to ssh. This is especially useful in scripts, or when you have more than 2 or 3 commands (esp. any control statements or loops)

$ ssh user@remoteserver << EOF
> # commands go here
> pwd
> # as many as you want
> # finish with EOF
> EOF
output, if any, of commands will display
$ # returned to your current shell prompt

If you do this on the command line, you'll get a stdin prompt to write your commands. On the command line, the SSH connection won't even be attempted until you indicate completion with EOF. So you won't see results as you go, but you can Ctrl-C to get out and start over. Whether on the command line or in a script, you wrap up the sequence of commands with EOF. You'll be returned to your normal shell at that point.

Upvotes: 6

Sean
Sean

Reputation: 29790

You could run xargs on the remote side:

$ echo "$argument" | ssh root@remote_server 'cd /root/dir; xargs -0 ./run.sh'

This avoids any quoting issues entirely--unless your argument has null characters in it, I suppose.

Upvotes: 2

Related Questions