The following does not work for me:
ssh user@remote.server \"k=5; echo $k;\"
it just returns an empty line.
How can I assign a variabl
Given this invocation:
ssh user@remote.server "k=5; echo $k;"
the local shell is expanding $k
(which most likely isn't set) before it is executing ssh ...
. So the command that actually gets passed to the remote shell once the connection is made is k=5; echo ;
(or k=5; echo something_else_entirely;
if k
is actually set locally).
To avoid this, escape the dollar sign like this:
ssh user@remote.server "k=5; echo \$k;"
Alternatively, use single quotes instead of double quotes to prevent the local expansion. However, while that would work on this simple example, you may actually want local expansion of some variables in the command that gets sent to the remote side, so the backslash-escaping is probably the better route.
For future reference, you can also type set -x
in your shell to echo the actual commands that are being executed as a help for troubleshooting.