1827857 Members
1754 Online
109969 Solutions
New Discussion

bash question

 
George Liu_4
Trusted Contributor

bash question

Hi Forum,

What is an elegant way to assign multiple variables into an array in bash. For example,
Gien the two records below, I would like to see the output
u[1]= named
u[2]= quagga
v[1]= 25
v[2]= 92
named:x:25:25:Named:/var/named:/sbin/nologin
quagga:x:92:92:Quaggasuite:/var/run/quagga:/sbin/nologin

Thanks,
5 REPLIES 5
Ivan Ferreira
Honored Contributor

Re: bash question

Should be something like this:


u[1]=`cut -d ":" -f 1 $RECORD`
v[1]=`cut -d ":" -f 3 $RECORD`


To print the value use:

echo ${u[1]}
echo ${v[1]}

You will need a While and a counter to process all lines of the passwd file.
Por que hacerlo dificil si es posible hacerlo facil? - Why do it the hard way, when you can do it the easy way?
George Liu_4
Trusted Contributor

Re: bash question

Ivan, Thanks.
Probably I didn't describe my problem clear. The entry number in the record file is unknown. So using "while" statement is not a good option.
My goal is to use u[i] as a key to lookup its corresponding field v[i]. The lookup operations are used multiple times.
Ivan Ferreira
Honored Contributor

Re: bash question

Why while is not an option? I was thinking in something like this:


#!/bin/bash
i=1
while read LINE
do
u[i]=`echo $LINE | cut -d ":" -f 1`
v[i]=`echo $LINE | cut -d ":" -f 3`
let "i++"
done < /etc/passwd

for n in `seq $i`
do
echo "Showing the $n element"
echo "Username: ${u[$n]}, USERID: ${v[$n]}"
done

Por que hacerlo dificil si es posible hacerlo facil? - Why do it the hard way, when you can do it the easy way?
Ralph Grothe
Honored Contributor

Re: bash question

The Bash syntax for declaration and definition in one go would be

declare -a u=(named quagga) v=(25 92)

But if you are reading the data from you passwd you could also parse entries from it and assign user and uid arrays in a loop like this

declare -i i=0;while read l;do u[i]=$(echo $l|cut -d: -f1) v[i++]=$(echo $l|cut -d: -f3);done < /etc/passwd

Please, note that index counting starts with 0.

Madness, thy name is system administration
George Liu_4
Trusted Contributor

Re: bash question

I am closing this thread. Thank you for your help.