LDP/LDP/guide/docbook/abs-guide/read-redir.sh

58 lines
1.7 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
read var1 <data-file
echo "var1 = $var1"
# var1 set to the entire first line of the input file "data-file"
read var2 var3 <data-file
echo "var2 = $var2 var3 = $var3"
# Note non-intuitive behavior of "read" here.
# 1) Rewinds back to the beginning of input file.
2001-09-04 13:27:31 +00:00
# 2) Each variable is now set to a corresponding string,
# separated by whitespace, rather than to an entire line of text.
2001-07-10 14:25:50 +00:00
# 3) The final variable gets the remainder of the line.
# 4) If there are more variables to be set than whitespace-terminated strings
# on the first line of the file, then the excess variables remain empty.
echo "------------------------------------------------"
# How to resolve the above problem with a loop:
while read line
do
echo "$line"
done <data-file
# Thanks, Heiner Steven for pointing this out.
echo "------------------------------------------------"
2004-01-26 00:03:37 +00:00
# Use $IFS (Internal Field Separator variable) to split a line of input to
2001-09-04 13:27:31 +00:00
# "read", if you do not want the default to be whitespace.
2001-07-10 14:25:50 +00:00
echo "List of all users:"
2001-09-04 13:27:31 +00:00
OIFS=$IFS; IFS=: # /etc/passwd uses ":" for field separator.
2001-07-10 14:25:50 +00:00
while read name passwd uid gid fullname ignore
do
echo "$name ($fullname)"
done </etc/passwd # I/O redirection.
2005-10-21 13:31:28 +00:00
IFS=$OIFS # Restore original $IFS.
2001-07-10 14:25:50 +00:00
# This code snippet also by Heiner Steven.
2003-01-06 21:25:36 +00:00
# Setting the $IFS variable within the loop itself
#+ eliminates the need for storing the original $IFS
#+ in a temporary variable.
# Thanks, Dim Segebart, for pointing this out.
echo "------------------------------------------------"
echo "List of all users:"
while IFS=: read name passwd uid gid fullname ignore
do
echo "$name ($fullname)"
done </etc/passwd # I/O redirection.
echo
echo "\$IFS still $IFS"
2001-07-10 14:25:50 +00:00
exit 0