Shell script

Charles Steinkuehler charles at steinkuehler.net
Tue Nov 11 22:48:47 CST 2003


brad wrote:
> I have a tab delimited list of usernames and passwords that I need to
> run a set of system commands on.  I was thinking maybe I could build a
> for loop and assign the first entry on the line as $x and the second
> entry on the line as $y.  Is this possible?  Or am I going to have to
> use sed or awk?

<code>
#!/bin/sh
myprocedure () {
   local IFS='	'	# There's a tab in there!
   while read USER PASS JUNK
   do
     # Do your thing here
     echo User: $USER
     echo Pass: $PASS
   done
}

myprocedure < /path/to/file
<code>

Of course, there are about a zillion other possible ways to do this, and 
lots of features you can add to the above.  One of my personal favorites 
is to support blank-space and comments by adding a simple case statement 
inside the do loop:

<code>
     # Skip comments and blank lines
     case "$USER" in
       #*|"") continue ;;
     esac
</code>

If you don't need to mess with IFS (to change whitespace to only tab, 
default is tab, space, and newline), you can even do the above pretty 
easily on the command line:

[admin at mongoose config]$ while read A B C
 > do
 > echo $A
 > echo $B
 > echo $C
 > echo -----
 > done </my/text/file

<output appears here :>

NOTE:  When using read to grab info from a file like this (or in 
general) it's always wise to include one more parameter than you 
currently support.  If you only read two variables, and there are more 
than two fields in your file, you'll get all the extras jammed into the 
last read variable:

$ echo 1 2 3 4 | ( read A B ; echo $A ; echo $B ; )
1
2 3 4
$ echo 1 2 3 4 | ( read A B C ; echo $A ; echo $B ; )
1
2
$

...hence the third variable "JUNK" in the above example.

-- 
Charles Steinkuehler
charles at steinkuehler.net




More information about the Kclug mailing list