Reputation: 695
Have been trying to find away to do array in sh shell script. Other than BASH etc. have not found much, other than arrays not supported in sh.
Here's what I've come up with using setvar and eval. Is there a better way? Any way to eliminate setvar and/or eval?
#!/bin/sh
# FreeBSD 11.1
# Kind of an array workaround.
echo -e "Simulated array creation and element assignment using dynamic index."
array() {
i=0
for x in $2
do
setvar ${1}_${i} $x # any way to do without setvar?
i=$((i+1))
done
setvar ${1}_cnt $i
}
array "my_arry" "a b c"
echo -e "\nSimulated array element access using dynamic index."
i=0
while [ $i -lt $my_arry_cnt ]
do
eval aev=\${my_arry_${i}} # any way to do without eval?
i=$((i+1))
echo $aev
done
echo -e "\nSimulated array element access using static index."
echo ${my_arry_0}
echo ${my_arry_1}
echo ${my_arry_2}
Upvotes: 0
Views: 1539