3 ms·
POSIX shells don't allow arrays, but they can be mimiced with eval. This function will construct a set of related variables that simulate an array: parr_add
by chasil 5y ago
POSIX shells don't allow arrays, but they can be mimiced with eval. This function will construct a set of related variables that simulate an array:
parr_add () { # $1:array $2:value
eval parr_c=${1}_c
parr_c=$((0+$parr_c))
eval ${1}_${parr_c}=\"$2\"
parr_c=$((1+$parr_c))
eval ${1}_c=$parr_c
unset parr_c
}
I could call this function from a loop that reads the password file:
IFS=:
while read user pw uid gid comm home shell <&9
do parr_add acc "$user"
done 9< /etc/passwd
Then, I could access these "array elements" in a loop:
count=0
while [ $acc_c -gt $count ]
do eval user=\$acc_$count
printf %s\\n "$user"
count=$((1+count))
done
Example run:
$ ./parr.sh | head -5
root
bin
daemon
adm
lp
It isn't that hard to survive without arrays.