0

I'd like execute command like this:

ssh remote_host export ENV_1=a && echo $ENV_1

But it turns out ENV_1 is empty, is there anything I did wrong ? Thanks

zjffdu
  • 113

1 Answers1

3

ENV_1 is empty because it's ENV_1 of your local shell. The && in your code is interpreted by your local shell and $ENV_1 gets substituted by your local shell.

ssh is smart enough to build a remote command from multiple arguments. Example:

ssh remote_host 'echo 1 2'
ssh remote_host 'echo 1' 2
ssh remote_host echo 1 2

The remote command will be echo 1 2 in each case, but it will be built from echo 1 2 (1 argument) or echo 1, 2 (2 arguments) or echo, 1, 2 (3 arguments) respectively. There are more possibilities.

It seems you wanted export ENV_1=a && echo $ENV_1 to be the remote command. Well, your local shell saw && and interpreted the whole line as ssh … && echo $ENV_1.

You should escape or quote && to protect it from the local shell. But if you do nothing more, $ENV_1 will still be substituted (by an empty string) by the local shell. You also need to escape $ or single-quote the variable.

The best thing is to quote the entire remote command. You don't want the variable to be expanded locally, so at least $ENV_1 should be single-quoted. In your desired command there's nothing that shouldn't be single-quoted, you can single-quote the entire remote command. But when it gets to the remote shell, the variable should be double-quoted. So this:

ssh remote_host 'export ENV_1=a && echo "$ENV_1"'

The variable won't be expanded locally because the outer quotes matter. Locally single-quotes are the outer ones.

You can find broader analysis in my answer to How to execute complex command line over ssh?
If your local shell is Bash then check How to single-quote or escape the whole command line in Bash conveniently?