Usual arrays are looped over using the indices. For my application I need to use an independent variable to extract values from array.
#!/bin/bash
# Author : Ankit
echo "Please enter the number of files (max index number of file): "
read iv
fname="t3p_"
echo "You entered: $iv, $fname" ;
#---------------------------------------------------------------------------------------------
#Reference values
refxa=(2.0 3.0 4.0)
refza=(1.0 6.0 7.0)
#---------------------------------------------------------------------------------------------
rm result.txt
#echo $iv,$fname
i=1
while [ $i -lt $(($iv+1)) ] ; do
xxn=5
zzn=19
refxn=$(echo $refxa | awk '{print $i}')
refzn=$(echo $refza | awk '{print $i}')
delta_x=`echo $xxn - $refxn | bc -l`
delta_z=`echo $zzn - $refzn | bc -l`
printf "%f\t%f\t%f\t%f\t%f\n" "$i" "$xxn" "$delta_x" "$zzn" "$delta_z" >> result.txt
i=$[$i+1]
done
echo -e "------------------------------------------------------------------------------------"
cat result.txt
My question :
- As seen above I want to subtract value
xxnfrom ith array element($i) which is the index of the loop. How to access the array element using the variable$i. (Using array index is not an option since in my script $i is related to several other parameters and that code is not shown here.)
I tried ${refxa[i]} which did not work.
Expected output (3rd and 5th column are xxn-refxn[i] and zzn-refzn[i]:
You entered: 3, t3p_
------------------------------------------------------------------------------------
1.000000 5.000000 3.000000 19.000000 18.000000
2.000000 5.000000 2.000000 19.000000 13.000000
3.000000 5.000000 1.000000 19.000000 12.000000
${refxa[i]}is not valid and it has to be${refxa[$i]}, right?ith array element($i) which is the index... laterUsing array index is not an option... bogus. Anyway - in bash the arrays has zero-based indexing - e.g. the first element is${arr[0]}.