| 1 | #!/bin/bash |
| 2 | # redir2.sh |
| 3 | |
| 4 | if [ -z "$1" ] |
| 5 | then |
| 6 | Filename=names.data # Default, if no filename specified. |
| 7 | else |
| 8 | Filename=$1 |
| 9 | fi |
| 10 | #+ Filename=${1:-names.data} |
| 11 | # can replace the above test (parameter substitution). |
| 12 | |
| 13 | count=0 |
| 14 | |
| 15 | echo |
| 16 | |
| 17 | while [ "$name" != Smith ] # Why is variable $name in quotes? |
| 18 | do |
| 19 | read name # Reads from $Filename, rather than stdin. |
| 20 | echo $name |
| 21 | let "count += 1" |
| 22 | done <"$Filename" # Redirects stdin to file $Filename. |
| 23 | # ^^^^^^^^^^^^ |
| 24 | |
| 25 | echo; echo "$count names read"; echo |
| 26 | |
| 27 | exit 0 |
| 28 | |
| 29 | # Note that in some older shell scripting languages, |
| 30 | #+ the redirected loop would run as a subshell. |
| 31 | # Therefore, $count would return 0, the initialized value outside the loop. |
| 32 | # Bash and ksh avoid starting a subshell *whenever possible*, |
| 33 | #+ so that this script, for example, runs correctly. |
| 34 | # (Thanks to Heiner Steven for pointing this out.) |
| 35 | |
| 36 | # However . . . |
| 37 | # Bash *can* sometimes start a subshell in a PIPED "while-read" loop, |
| 38 | #+ as distinct from a REDIRECTED "while" loop. |
| 39 | |
| 40 | abc=hi |
| 41 | echo -e "1\n2\n3" | while read l |
| 42 | do abc="$l" |
| 43 | echo $abc |
| 44 | done |
| 45 | echo $abc |
| 46 | |
| 47 | # Thanks, Bruno de Oliveira Schneider, for demonstrating this |
| 48 | #+ with the above snippet of code. |
| 49 | # And, thanks, Brian Onn, for correcting an annotation error. |