3

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

2
  • What happens when you run ssh remServer 'ls' interactively? Could you check in the shell configuration files (.bashrc and so on) on the remote system to see if there is an alias for the ls command? Commented Mar 1, 2018 at 16:36
  • Hello! Thanks for your viewing. Running interactively, I get a simple listing of files (as expected) - just as I do when on the remote server itself (so nothing changing the ls command there). Commented Mar 1, 2018 at 16:58

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.