I'm not quite sure what the issue is. I'm on Kali Linux 2.0 right now, fresh install. The following worked on Ubuntu 14.04 but it's not working anymore (maybe I accidentally changed it?). It looks correct to me, but every time it runs it blocks.

backup_folder=$(ssh -i /home/dexter/.ssh/id_rsa $server 'ls -t '$dir' | head -1')

This is part of a larger script. $server and $dir are set. When I run the command alone, I get the correct output, but it doesn't end the connection.

  • 2
    just FYI, it works for me on Ubuntu 15.04. I also don't see anything wrong on the first sight. – Jakuje Oct 15 '15 at 21:36
  • 1
    You may want to quote the $dir expansion, lest you might run into problems if $dir ever expands to a path that contains whitespace or shell metacharacters. – a CVn Apr 15 '16 at 9:14

I'm not entirely sure why the command would hang, but you don't need to run the whole pipeline on the server. It's enough to do the ls there:

backup_folder=$( ssh -i keyfile "$server" "ls -t -- '$dir'" | head -n 1 )

Note that this quotes the $dir value on the remote side (it will still be expanded locally). The head will run locally.

This also comes with the caveats mentioned in the answers to "Why *not* parse `ls` (and what to do instead)?".


I came across the same problem and by consulting man ssh, I found out:

# Problem: if you copy & paste those two lines together into a shell, 
# then the second command is not executed. 
# But if you run each line on its own, it will work
srcdirs=$(ssh myserver "ls -1 /home")
echo "$srcdirs"   # command is also not recorded by history

# Solution: Redirect stdin from /dev/null
srcdirs=$(ssh -n myserver "ls -1 /home")
echo "$srcdirs"

Hope, this solves your issue...

New contributor
A-Man is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

I have had the same issue recently, probably you should add a redirection to stdout at the end of the command, like so:

backup_folder=$(ssh -i /home/dexter/.ssh/id_rsa $server 'ls -t '$dir' | head -1' 2>&1)
  • That would cause error messages to be part of the $backup_folder string. – Kusalananda Jun 20 '18 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.