| 1 | #!/bin/bash |
| 2 | |
| 3 | # This is an alternate form of the preceding script. |
| 4 | |
| 5 | # Suggested by Heiner Steven |
| 6 | #+ as a workaround in those situations when a redirect loop |
| 7 | #+ runs as a subshell, and therefore variables inside the loop |
| 8 | # +do not keep their values upon loop termination. |
| 9 | |
| 10 | |
| 11 | if [ -z "$1" ] |
| 12 | then |
| 13 | Filename=names.data # Default, if no filename specified. |
| 14 | else |
| 15 | Filename=$1 |
| 16 | fi |
| 17 | |
| 18 | |
| 19 | exec 3<&0 # Save stdin to file descriptor 3. |
| 20 | exec 0<"$Filename" # Redirect standard input. |
| 21 | |
| 22 | count=0 |
| 23 | echo |
| 24 | |
| 25 | |
| 26 | while [ "$name" != Smith ] |
| 27 | do |
| 28 | read name # Reads from redirected stdin ($Filename). |
| 29 | echo $name |
| 30 | let "count += 1" |
| 31 | done # Loop reads from file $Filename |
| 32 | #+ because of line 20. |
| 33 | |
| 34 | # The original version of this script terminated the "while" loop with |
| 35 | #+ done <"$Filename" |
| 36 | # Exercise: |
| 37 | # Why is this unnecessary? |
| 38 | |
| 39 | |
| 40 | exec 0<&3 # Restore old stdin. |
| 41 | exec 3<&- # Close temporary fd 3. |
| 42 | |
| 43 | echo; echo "$count names read"; echo |
| 44 | |
| 45 | exit 0 |