Of course, you can set the environment variable inside the command, however you'll have to be careful about quoting: remember that your shell is going to parse your local command line, and then the remote shell will have a go on the string it receives.
If you want a variable to get the same value on the server that it has on the client, try the SendEnv
option:
ssh -o SendEnv=MYVAR server.example.com mycommand
This requires support from the server, though. With OpenSSH, the variable name has to be authorized in /etc/sshd_config
.
If the server only allows certain specific variable names, you can work around that; for example a common setup allows LC_*
through, and you can do the following:
ssh -o SendEnv=LC_MYVAR server.example.com 'MYVAR=$LC_MYVAR; unset LC_MYVAR; export MYVAR; mycommand'
If even LC_*
is not an option, you can pass information in the TERM
environment variable, which is always copied (there may be a length limit however). You'll still have to make sure that the remote shell doesn't restrict the TERM
variable to designate a known terminal type. Pass the -t
option to ssh if you're not starting a remote interactive shell.
env TERM="extra information:$TERM" ssh -t server.example.com 'MYVAR=${TERM%:*}; TERM=${TERM##*:}; export MYVAR; mycommand'
Another possibility is to define the variable directly in the command:
ssh -t server.example.com 'export MYVAR="extra information"; mycommand'
Thus, if passing a local variable:
ssh -t server.example.com 'export MYVAR='"'$LOCALVAR'"'; mycommand'
However, beware of quoting issues: the value of the variable will be interpolated directly into the shell snippet executed on the remote side. The last example above assumes that $LOCALVAR
does not contain any single quotes ('
).
2
Possible duplicate of how can I pass an environment variable through an ssh command?
– Tonin – 2015-12-21T12:32:43.0271Other way round, as this is already more popular. It doesn't matter it's older. – kenorb – 2015-12-23T10:10:05.563
2You question needs to be a liiittle more specific. – Ignacio Vazquez-Abrams – 2010-07-13T17:09:24.637
3The question was clear enough to me. However, from the
ssh
man page, I don't see any way to do that other than setting the variable manually once you've logged in to the server, unless you modify ~/.ssh2/environment. – garyjohn – 2010-07-13T17:23:24.493Is it a different variable each time? Or a different value? – Paused until further notice. – 2010-07-13T17:52:39.883
Different value each time. – Ross Rogers – 2010-07-13T20:37:01.163