| 1 | #!/bin/bash |
| 2 | |
| 3 | read var1 <data-file |
| 4 | echo "var1 = $var1" |
| 5 | # var1 set to the entire first line of the input file "data-file" |
| 6 | |
| 7 | read var2 var3 <data-file |
| 8 | echo "var2 = $var2 var3 = $var3" |
| 9 | # Note non-intuitive behavior of "read" here. |
| 10 | # 1) Rewinds back to the beginning of input file. |
| 11 | # 2) Each variable is now set to a corresponding string, |
| 12 | # separated by whitespace, rather than to an entire line of text. |
| 13 | # 3) The final variable gets the remainder of the line. |
| 14 | # 4) If there are more variables to be set than whitespace-terminated strings |
| 15 | # on the first line of the file, then the excess variables remain empty. |
| 16 | |
| 17 | echo "------------------------------------------------" |
| 18 | |
| 19 | # How to resolve the above problem with a loop: |
| 20 | while read line |
| 21 | do |
| 22 | echo "$line" |
| 23 | done <data-file |
| 24 | # Thanks, Heiner Steven for pointing this out. |
| 25 | |
| 26 | echo "------------------------------------------------" |
| 27 | |
| 28 | # Use $IFS (Internal Field Separator variable) to split a line of input to |
| 29 | # "read", if you do not want the default to be whitespace. |
| 30 | |
| 31 | echo "List of all users:" |
| 32 | OIFS=$IFS; IFS=: # /etc/passwd uses ":" for field separator. |
| 33 | while read name passwd uid gid fullname ignore |
| 34 | do |
| 35 | echo "$name ($fullname)" |
| 36 | done </etc/passwd # I/O redirection. |
| 37 | IFS=$OIFS # Restore original $IFS. |
| 38 | # This code snippet also by Heiner Steven. |
| 39 | |
| 40 | |
| 41 | |
| 42 | # Setting the $IFS variable within the loop itself |
| 43 | #+ eliminates the need for storing the original $IFS |
| 44 | #+ in a temporary variable. |
| 45 | # Thanks, Dim Segebart, for pointing this out. |
| 46 | echo "------------------------------------------------" |
| 47 | echo "List of all users:" |
| 48 | |
| 49 | while IFS=: read name passwd uid gid fullname ignore |
| 50 | do |
| 51 | echo "$name ($fullname)" |
| 52 | done </etc/passwd # I/O redirection. |
| 53 | |
| 54 | echo |
| 55 | echo "\$IFS still $IFS" |
| 56 | |
| 57 | exit 0 |