0

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)?

1

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

The actual assignment for us is to write a script that will output something like that in a table, but on multiple files from a directory, the script expects a single command line argument which is the directory. So I am trying to write this part that will open a file and store them into the array, and call it later on to do the table. From my understanding I cant pipe cat here with while read, how should I do it otherwise?
I have provided you working code. Instead of pipe use done < file to read it.
Ah, right, done <file should do the trick, I totally missed that part, thank you!
One more question, if I need to do a loop for the above code and have it work on every file in a given directory, and the array names will be the file name instead of a, how does that work? I tried using a for loop but it didn't quite work.
Creating dynamic array names is not trivial. See my answer here for more details: stackoverflow.com/a/21626692/548225

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.