Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)
do
   echo "Connecting to " $machine
   ssh $machine ls -la && exit
done

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. –  The Justist Mar 5 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 at 16:14

3 Answers 3

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 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;
do
  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
EOF
share|improve this answer

Your Answer

 
discard

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.