BASH + Best method of converting fields to variables

Rick Stevens rstevens at vitalstream.com
Sat Jul 17 00:35:02 UTC 2004


Ow Mun Heng wrote:
> Guys,
> 
> 	Writing a batch_create_new_user script.
> input is a file with this format
> 
> Username:Full Name:Default Group:Default Shell:Home Directory:Password
>  
> and the using those fields ($1 $2 $3 etc) and passing then to the useradd program
> 
> I'm having some trouble getting bash to get the positional fields into variables which I
> can then plug into useradd
> 
> eg:
> pseudo code
> for each line in input file
>   do
> 	username=$1
> 	name=$2
> 	useradd -c "$2" $1
>   done
> 
> I ended up using awk, which works but seems complicated
> 
> 	eval `awk -F ':' \
>         '{printf ("useradd -c \"%s\" ",$2)}; \
>         length($3)>0 {printf ("-g %s ",$3)}; \
>         length($4)>0 {printf ("-s %s ",$4)}; \
>         length($5)>0 {printf ("-d %s ",$5)}; \
>         {printf ("%s\n;",$1)};' $1`
> 
> Can it be done using bash itself? (without calling awk)

Not really, because bash delimits fields with spaces, not colons.

> Actually I was hoping I can get awk to get the fields for the variables
> 
> psuedo code
> username = awk -F: {'print $1}'
> name = awk -F: {'print $2}'
> 
> Any takers??
> 
> BTW, what's the best way to check the number of fields in the input file?
> I was thinkning of counting how many ":" there are in each line. But can't
> figure out how to actually _do_ it.

awk's "$NF" variable contains the number of fields in the current input
record.
----------------------------------------------------------------------
- Rick Stevens, Senior Systems Engineer     rstevens at vitalstream.com -
- VitalStream, Inc.                       http://www.vitalstream.com -
-                                                                    -
-    When you don't know what to do, walk fast and look worried.     -
----------------------------------------------------------------------





More information about the users mailing list