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?

  • 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
  • 1
    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

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.


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

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

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.