1

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.

I like to code
  • 201
  • 2
  • 9
  • 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. – user Apr 15 '16 at 09:14

3 Answers3

0

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)?".

Kusalananda
  • 333,661
0

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...

A-Man
  • 1
-1

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)