2001-07-10 14:25:50 +00:00
|
|
|
#!/bin/bash
|
2005-03-21 13:51:11 +00:00
|
|
|
# redir2.sh
|
2001-07-10 14:25:50 +00:00
|
|
|
|
|
|
|
if [ -z "$1" ]
|
|
|
|
then
|
2002-04-01 16:04:17 +00:00
|
|
|
Filename=names.data # Default, if no filename specified.
|
2001-07-10 14:25:50 +00:00
|
|
|
else
|
|
|
|
Filename=$1
|
|
|
|
fi
|
2002-04-01 16:04:17 +00:00
|
|
|
#+ Filename=${1:-names.data}
|
|
|
|
# can replace the above test (parameter substitution).
|
2001-07-10 14:25:50 +00:00
|
|
|
|
|
|
|
count=0
|
|
|
|
|
|
|
|
echo
|
|
|
|
|
|
|
|
while [ "$name" != Smith ] # Why is variable $name in quotes?
|
|
|
|
do
|
2001-09-04 13:27:31 +00:00
|
|
|
read name # Reads from $Filename, rather than stdin.
|
2001-07-10 14:25:50 +00:00
|
|
|
echo $name
|
|
|
|
let "count += 1"
|
2014-07-05 13:38:40 +00:00
|
|
|
done <"$Filename" # Redirects stdin to file $Filename.
|
2001-10-15 14:21:41 +00:00
|
|
|
# ^^^^^^^^^^^^
|
2001-07-10 14:25:50 +00:00
|
|
|
|
|
|
|
echo; echo "$count names read"; echo
|
|
|
|
|
2005-03-21 13:51:11 +00:00
|
|
|
exit 0
|
|
|
|
|
2002-04-01 16:04:17 +00:00
|
|
|
# Note that in some older shell scripting languages,
|
|
|
|
#+ the redirected loop would run as a subshell.
|
2005-03-21 13:51:11 +00:00
|
|
|
# Therefore, $count would return 0, the initialized value outside the loop.
|
|
|
|
# Bash and ksh avoid starting a subshell *whenever possible*,
|
|
|
|
#+ so that this script, for example, runs correctly.
|
|
|
|
# (Thanks to Heiner Steven for pointing this out.)
|
2001-07-10 14:25:50 +00:00
|
|
|
|
2006-03-06 14:21:00 +00:00
|
|
|
# However . . .
|
|
|
|
# Bash *can* sometimes start a subshell in a PIPED "while-read" loop,
|
|
|
|
#+ as distinct from a REDIRECTED "while" loop.
|
2005-03-21 13:51:11 +00:00
|
|
|
|
|
|
|
abc=hi
|
|
|
|
echo -e "1\n2\n3" | while read l
|
|
|
|
do abc="$l"
|
|
|
|
echo $abc
|
|
|
|
done
|
|
|
|
echo $abc
|
|
|
|
|
2006-03-06 14:21:00 +00:00
|
|
|
# Thanks, Bruno de Oliveira Schneider, for demonstrating this
|
|
|
|
#+ with the above snippet of code.
|
|
|
|
# And, thanks, Brian Onn, for correcting an annotation error.
|