0

I need to perform an operation on a list of server, through SSH.

I am using sshpass, and that operation might fail, however it's supposed to happen a few time, and the script should still continue.

#!/bin/bash

while read address; do
    echo -n "$address "
    sshpass -p password ssh -o StrictHostKeyChecking=no user@$address 'ls /path/to/some/dir'
done < address-list

However, the command ran through ssh fail on the first host, and the script immediately exit.

How can I have the loop continue executing, no matter what ? Adding an exit after my command doesn't fix this, and unsetting exit on error set +e doesn't work either.

  • 1
    Your snippet seems to be missing a backtick (`) – Panki Jan 8 at 8:58
  • Can you post the whole script, and let know what other options you are setting along with set -e – Inian Jan 8 at 9:02
  • @Panki good catch, fixed it. – user96649 Jan 8 at 9:04
  • @Inian The script is as simple as that, basically – user96649 Jan 8 at 9:05
1

ssh will inherit the standard input stream from the loop and read as much as possible from it, meaning it will read read the remaining lines from your address-list file. Since ssh is reading the remaining lines from the file, the loop will only ever do a single iteration. Technically, the script does not terminate prematurely or fail in any way, it just does not do what you want it to do.

To avoid this, use ssh -n to prevent ssh from reading from standard input:

while read address; do
    echo -n "$address "
    sshpass -p password ssh -n -o StrictHostKeyChecking=no "user@$address" 'ls /path/to/some/dir'
done < address-list

ssh behaves in this way so that you would be able to pass data into some program started on the remote host, but as you have discovered, in your case this will prevent your loop from functioning correctly.

  • Thanks you for the explanation, and for the working solution. – user96649 Jan 8 at 9:20

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.