Re: BASH + Best method of converting fields to variables

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Friday, Jul 16th 2004 at 17:23 -0700, quoth Ow Mun Heng:

=>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)
=>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.

Easy peasy japanesy.

#! /bin/bash
typeset IFS=:

while read f1 f2 f3 f4 f5
do
    useradd -c f2 -g $f3 -s $f4 -d $f5 $f1
done < input_file


But if all the fields (except for the first one are optional) then
just do dis:

#! /bin/bash
typeset IFS=:

while read f1 f2 f3 f4 f5
do
    cmd=useradd
    [[ -n "$f2" ]] && cmd="$cmd -c $f2"
    [[ -n "$f3" ]] && cmd="$cmd -g $f3"
    [[ -n "$f4" ]] && cmd="$cmd -s $f4"
    [[ -n "$f5" ]] && cmd="$cmd -d $f5"
    cmd="$cmd $f1"
    eval "$cmd"
done < input_file

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



[Index of Archives]     [Current Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]     [Fedora Docs]

  Powered by Linux