I have a shell script that has to find the newest file on a remote host. I have this bit:

ssh -q $HOSTNAME -t ls -t -1 /path/to/somewhere/ | head -n 1

It prints the first line, then waits and doesn't terminate.

However if I remove the | head -n 1, then it'll print all the files in order and then terminate regularly and return control flow to my terminal. So the SSH command part is terminating fine, but not the head part. What's going on? How do I get the head to work?

  • Works for me in bash, outside of a script. Perhaps your variables aren't what you expect, or ssh is broken somehow, try removing the -q or perhaps do 2>&1 to catch stderr too.. Mar 2, 2012 at 13:39
  • Why do you need -t for executing just ls?
    – adamo
    Mar 2, 2012 at 14:17

3 Answers 3


It hangs because it doesn't get any input. Try doing just head -n 1 .

This will ensure that piping to head will occur in the pseudo-tty

ssh -q $HOSTNAME -t "ls -t -1 /path/to/somewhere/ | head -n 1"

I have to admit that in Debian Squeeze and Ubuntu server 10.4 I wasn't able to reproduce that.

Care to give more information like without the "-q",distro,etc.


How about

ssh -q $HOSTNAME -t "ls -t -1 /path/to/somewhere/" | head -n 1
  • No change, same affect, head hangs Mar 2, 2012 at 12:58
  • 2
    What about wrapping the | head -n1 inside the double-quoted bit too. Why does that bit need to happen locally? Mar 2, 2012 at 13:41

Why not try it this way:

ssh -q $HOSTNAME -t ls -tr -1 /some/path | tail -n 1

This will let you know if the head command is at fault. Your previous command seems to work fine on my machine. Strange stuff.

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.