Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture output of bash script over ssh within script

Tags:

bash

ssh

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

like image 634
Kid Codester Avatar asked Aug 29 '26 07:08

Kid Codester


1 Answers

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"
like image 125
that other guy Avatar answered Aug 31 '26 20:08

that other guy