I am aware of this discussion: Running A Bash Script Over SSH
However, I have a somewhat varied take on it - and it's got me stumped.
I have an ssh alias in my ~/.ssh/config called remServer to which I can ssh just fine. I'd like to run some remote commands on that server and deal with the output on the local server.
My problem comes to substituting variables into the ssh commands (such an elementary subject) but I'm missing something here.
Here's the issue:
#this works
op="ls"
cmd="ssh remServer '$op'"
res=`$cmd`
echo $res
#this doesn't
op="ls -lt"
cmd="ssh remServer '$op'"
res=`$cmd`
echo $res
No matter how many ways I use single or double quotes, I only get back something along the lines of:
bash ls -lt command not found
Since you pass in literal single quotes, the command executed becomes 'ls -lt' which gives the same error locally too (as opposed to ls -lt without quotes).
The easiest solution is just removing the quotes:
op="ls -lt"
cmd="ssh remServer $op"
res=`$cmd`
echo $res
The better solution is using proper arrays and escaping:
op=(ls -lt)
cmd=(ssh remServer "$(printf '%q ' "${op[@]}")" )
res=$("${cmd[@]}")
echo "$res"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With