Nick
Nick

Reputation: 1191

Bash array isn't working?

The following code is not outputting anything.

#!/bin/bash
declare -A a
cat input.txt | while read item value
do
if [ $item="owner" ] || [ $item="admin" ] || [ $item="loc" ] || [ $item="ser"]
then
a[$item]=$value
fi
done
echo ${a[owner]}

the input file is:

owner sysadmin group
admin ajr
loc S-309
ser 18r97
comment noisy fan

I need to create an array a only for index at owner, admin, loc and ser.

I was expecting an output for echo ${a[owner]} to be sysadmin group and so on.

Any help?

EDIT: I think it might have something to do with owner is sysadmin group, how do I read that (two words with space) into a variable (value)?

Upvotes: 0

Views: 773

Answers (1)

anubhava
anubhava

Reputation: 785146

It is because you're using a sub-shell by using pipe. All the changes made in the sub-shell are local to sub shell only and not reflected in parent shell.

Use this:

#!/bin/bash
declare -A a
while read item value
do
  if [ $item="owner" ] || [ $item="admin" ] || [ $item="loc" ] || [ $item="ser"]
  then
    a[$item]=$value
   fi
done < input.txt

echo ${a[owner]}
sysadmin group

Upvotes: 1

Related Questions