Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to connect to multiple machines specified in a file and perform 'ls' there.

That's what I've come up with:

for machine in $(cat machines)
   echo "Connecting to " $machine
   ssh $machine ls -la && exit

Apart from the fact that I need to 'cd' to a different directory before the 'ls', the loop ends after the first entry in the file. This first entry is my machine itself, if that is important.

What am I missing?

share|improve this question
I would guess that exit does shut your script down instead of your connection to the machine. Just a guess, though, am no expert on this subject. – Simon Klaver Mar 5 '14 at 15:48
As other people have pointed out the && exit doesn't need to be there. But if you want to have the && happen on the target machine instead of locally, the easiest way is to quote it, eg '&&'. – Graeme Mar 5 '14 at 16:14
up vote 9 down vote accepted

Your problem is here:

ssh $machine ls -la && exit

Your script sshs to the remote machine which runs your ls. ssh exits with success, && sees this and runs the next command which is exit, so your script exits!

You don't need the && exit at all. When ls finishes, the connection will close and ssh will complete. Just remove that bit and you'll be golden.

share|improve this answer
perfect, thanks! – FAS Mar 5 '14 at 15:49

You're not missing anything, you're adding something you shouldn't. The exit actually kills your session, it is not being run on the remote machine:

ssh foo@bar.com command && other_command
|---------------------|    |------------|
        |                        |----------> A completely separate command to be
        |                                     run if the ssh is successful 
        |-----------------------------------> The ssh command

Also, you don't need the cd (or the cat) at all, what you want to run is:

while read machine;
  echo "Connecting to " $machine
  ssh $machine ls -la /path/to/remote/directory
done < machines
share|improve this answer

exit isn't run remotely but on this side (and is unnecessary). If you need to perform more than one command (like cd, ls and possibly more), just pipe a script to ssh and execute it remotely with bash. Something like

cat <<EOF | ssh "$machine" bash
  cd "$remote_dir"
  ls -la
  exit #if you actually needed this, it would be here, but you don't
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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