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 variable on a remote session (ssh)?
Note: My question is not about how to pass local variables to my ssh session, but rather how to create and assign remote variables. (should be a pretty straight forward task?)
Edit:
In more detail I am trying to do this:
bkp=/some/path/to/backups
ssh user@remote.server "bkps=( $(find $bkp/* -type d | sort) );
echo 'number of backups: '${#bkps[@]};
while [ ${#bkps[@]} -gt 5 ]; do
echo ${bkps[${#bkps[@]}-1]};
#rm -rf $bkps[${#bkps[@]}-1];
unset bkps[${#bkps[@]}-1];
done;"
The find command works fine, but for some reason $bkps
does not get populated.
So my guess was that it would be a variable assignment issue, since I think I have checked everything else...
Given this invocation:
the local shell is expanding
$k
(which most likely isn't set) before it is executingssh ...
. So the command that actually gets passed to the remote shell once the connection is made isk=5; echo ;
(ork=5; echo something_else_entirely;
ifk
is actually set locally).To avoid this, escape the dollar sign like this:
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.