shell / awk arrays

I have a bash shell script that sources a data file, the data file has array values such as:

#--data file ---#
sg_name[0]="db1"
sg_size[0]="12892"
sg_allow[0]="50000"

sg_name[1]="db2"
sg_size[1]="12892"
sg_allow[1]="50000"

export sg_name sg_size sg_allow
#--end data file --#

In my shell script I source this file:
. /data/data.file

so all the array variables are available.

Is there a way to easily use these variables within 'awk' ?
Or, can awk source this file also to use the array variables?

Thanks

awk -v options does what you wish.

awk -v sg_name=${sg_name[0]} '{ print sg_name }'

nawk and recent versions gawk (GNU awk) can read exported variables via ENVIRON e.g.

$ WET=august
$ export WET
$ gawk 'BEGIN { print ENVIRON["WET"] }' file
august
$

I'm familiar with using the '-v' flag to set variables.

But I was wondering if it was possible to keep the same array structure in awk as it is in the shell.

I take it awk can not source that data file to utilize the array variables?

Maybe Im not wording this the best way :slight_smile:

Can you provide an example of how you plan to use it?

I don't think there is a way to automatically import all arrays to awk. You have to do it manually with -v I guess.

Heres something like what I have in a shell script:

. /data.file
anum="0"
while [ ! -z "${sg_name[${anum}]}" ]
do
echo "sg_name[${anum}]}"
echo "sg_size[${anum}]}"
echo "sg_allow[${anum}]}"
done

I'd like to continue to utilitize that array within awk the same way. But I guess the only way is to pass all variables via the '-v' flag.

. /data.file
anum=0 <-- Since this is meant as an integer you should not quote it
while [ ! -z "${sg_name[${anum}]}" ]
do
echo "sg_name[${anum}]}"
echo "sg_size[${anum}]}"
echo "sg_allow[${anum}]}"
((anum++)) #<-- You did not increment the anum value
done

I see, I was trying to type fast and missed the increment line...

Something I didn't realize though is "not quoting" if the variable is suppose to be an integer.

I usually typeset the variables in my scripts to declare them as integers.

typeset -i anum

In this case, if I set:

typeset -i anum
anum="0"

Does quoting over ride the typeset?