Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run 'export' command Over SSH

Tags:

bash

ssh

When I run the following from my bash shell:

bash -c '(export abc=123 && echo $abc)'

The output is "123". But when I run it over ssh:

ssh remote-host "bash -c '(export abc=123 && echo $abc)'"

There is no output. Why is this? Is there a way around this? That is, is there a way to set an environment variable for a command I run over ssh?

Note: When I replace echo $abc with something standard like echo $USER the ssh command prints out the username on the remote machine as expected since it is already set.

I am running RHEL 5 Linux with OpenSSH 4.3

like image 321
aaronstacy Avatar asked Jan 11 '11 22:01

aaronstacy


1 Answers

That is because when using

ssh remote-host "bash -c '(export abc=123 && echo $abc)'"

the variable gets expanded by the local shell (as it is the case with $USER) before ssh executes. Escape the $ by using \$ and it should do fine

ssh remote-host "bash -c '(export abc=123 && echo \$abc)'"

On a side note:

  • You don't need to export just for this.
  • You don't need to wrap it in ()

Like so:

ssh remote-host "bash -c 'abc=123 && echo \$abc'"

Heck, you can even leave out the bash -c ... stuff, as the ssh manpage states:

If command is specified, it is executed on the remote host instead of a login shell.

But these may be specific to your task ;)

like image 75
Marcus Borkenhagen Avatar answered Sep 29 '22 10:09

Marcus Borkenhagen