177

I have the following shell script. The purpose is to loop thru each line of the target file (whose path is the input parameter to the script) and do work against each line. Now, it seems only work with the very first line in the target file and stops after that line got processed. Is there anything wrong with my script?

#!/bin/bash
# SCRIPT: do.sh
# PURPOSE: loop thru the targets 

FILENAME=$1
count=0

echo "proceed with $FILENAME"

while read LINE; do
   let count++
   echo "$count $LINE"
   sh ./do_work.sh $LINE
done < $FILENAME

echo "\ntotal $count targets"

In do_work.sh, I run a couple of ssh commands.

oguz ismail
  • 1
  • 16
  • 47
  • 69
bcbishop
  • 2,193
  • 3
  • 20
  • 23

5 Answers5

270

The problem is that do_work.sh runs ssh commands and by default ssh reads from stdin which is your input file. As a result, you only see the first line processed, because the command consumes the rest of the file and your while loop terminates.

This happens not just for ssh, but for any command that reads stdin, including mplayer, ffmpeg, HandBrakeCLI, httpie, brew install, and more.

To prevent this, pass the -n option to your ssh command to make it read from /dev/null instead of stdin. Other commands have similar flags, or you can universally use < /dev/null.

that other guy
  • 116,971
  • 11
  • 170
  • 194
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 2
    Very useful, helped me to run this zsh oneliner: cat hosts | while read host ; do ssh $host do_something ; done – rat Jan 02 '18 at 16:43
  • 6
    @rat You still want to avoid the [useless `cat`.](/questions/11710552/useless-use-of-cat) You'd think a rodent in particular would be wary of this. – tripleee Jul 19 '19 at 08:45
  • `while read host ; do $host do_something ; done < /etc/hosts` would avoid it. That's quite a life saver, thanks! – rat Jul 19 '19 at 15:09
  • `httpie` is another command that reads STDIN by default, and will suffer from the same behavior when called inside a bash or fish loop. Use `http --ignore-stdin` or set standard input to `/dev/null` as above. – Raman Nov 15 '19 at 18:10
  • What will be the solution for `gcloud compute ssh` case? – JackTheKnife Aug 15 '23 at 22:57
51

A very simple and robust workaround is to change the file descriptor from which the read command receives input.

This is accomplished by two modifications: the -u argument to read, and the redirection operator for < $FILENAME.

In BASH, the default file descriptor values (i.e. values for -u in read) are:

  • 0 = stdin
  • 1 = stdout
  • 2 = stderr

So just choose some other unused file descriptor, like 9 just for fun.

Thus, the following would be the workaround:

while read -u 9 LINE; do
   let count++
   echo "$count $LINE"
   sh ./do_work.sh $LINE
done 9< $FILENAME

Notice the two modifications:

  1. read becomes read -u 9
  2. < $FILENAME becomes 9< $FILENAME

As a best practice, I do this for all while loops I write in BASH. If you have nested loops using read, use a different file descriptor for each one (9,8,7,...).

cmo
  • 3,762
  • 4
  • 36
  • 64
  • 10
    Thanks! this is actually the best solution here IMO – Iman Akbari Feb 25 '21 at 05:31
  • 3
    Thank you very much! This looks also like the best solution for me right know because with this one you don't need to find the problematic command if you have larger scripts. – ced-mos Jul 08 '21 at 10:32
  • 1
    Excellent solution! – Feriman Dec 16 '21 at 15:40
  • 1
    This !!! This one worked !!! – ambikanair Apr 08 '22 at 10:20
  • 1
    Thanks! This was the only solution that worked for me. – Abhijay Ghildyal May 22 '22 at 02:18
  • 1
    This is a really nice trick. It can be quite a surprise that arbitrary commands end up reading stdin. In my case it was `sloccount`. This is general solution that doesn't require reading command specific man pages (if any). – user1556435 Nov 08 '22 at 09:13
  • 1
    The best solution for this problem. Thanks buddy you saved me! – Mohammad Ala Amjadi Dec 18 '22 at 23:48
  • 1
    This is IMHO a better solution than the accepted one. There are other commands besides ssh that read stdin, messing up the while loop. This solution, to use a different file descriptor, allowed me to keep existing called infrastructure in the loop the same. This allowed me to avoid having to test interactions with sshpass, or other programs in the loop that might affect stdin. Thanks!! – Tim Bird Jan 18 '23 at 18:37
  • Thanks! this worked for me, saves amended the many ssh commands i had. Although i tried the preferred solution of Dogbane, adding the -n and – Red_badger Mar 09 '23 at 16:08
33

More generally, a workaround which isn't specific to ssh is to redirect standard input for any command which might otherwise consume the while loop's input.

while read -r line; do
   ((count++))
   echo "$count $line"
   sh ./do_work.sh "$line" </dev/null
done < "$filename"

The addition of </dev/null is the crucial point here, though the corrected quoting is also somewhat important for robustness; see also When to wrap quotes around a shell variable?. You will want to use read -r unless you specifically require the slightly odd legacy behavior you get for backslashes in the input without -r. Finally, avoid upper case for your private variables.

Another workaround of sorts which is somewhat specific to ssh is to make sure any ssh command has its standard input tied up, e.g. by changing

ssh otherhost some commands here

to instead read the commands from a here document, which conveniently (for this particular scenario) ties up the standard input of ssh for the commands:

ssh otherhost <<'____HERE'
    some commands here
____HERE
tripleee
  • 175,061
  • 34
  • 275
  • 318
5

ssh -n option prevents checking the exit status of ssh when using HEREdoc while piping output to another program. So use of /dev/null as stdin is preferred.

#!/bin/bash
while read ONELINE ; do
   ssh ubuntu@host_xyz </dev/null <<EOF 2>&1 | filter_pgm 
   echo "Hi, $ONELINE. You come here often?"
   process_response_pgm 
EOF
   if [ ${PIPESTATUS[0]} -ne 0 ] ; then
      echo "aborting loop"
      exit ${PIPESTATUS[0]}
   fi
done << input_list.txt
jacobm654321
  • 643
  • 6
  • 8
4

This was happening to me because I had set -e and a grep in a loop was returning with no output (which gives a non-zero error code).

tripleee
  • 175,061
  • 34
  • 275
  • 318
JonnyRaa
  • 7,559
  • 6
  • 45
  • 49