Issue
The following does not work for me:
ssh [email protected] "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 [email protected] "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...
Solution
Given this invocation:
ssh [email protected] "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 [email protected] "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.
Answered By - twalberg Answer Checked By - Marie Seifert (WPSolving Admin)