linuxbashshellfor-looppositional-parameter

Define variables with positional parameters using for loop in Bash script


Is there a way to define a bunch of positional-parameter variables using loop in Bash? For example, below is what I want to achieve

mid_1=$1   
freq_1=$2 
mid_2=$3
freq_2=$4
mid_3=$5
freq_3=$6
mid_4=$7   
freq_4=$8

my code:

q=4
q_len=$(( q*2+1 ))
all_var=()
j=1
l=2
for (( i=1; i<$q_len; i+=2 ))
do
declare mid_$j=\$$i freq_$j=\$$l
all_var+=(mid_$j freq_$j)
j=$(( j+1 ))
l=$(( l+2 ))
done

for item in "${all_var[@]}"; do echo -n "\$$item "; done;

At first, it looks right.

echo $mid_2
$3

Wrong. Define in bash, mid_2=$3, and echo $mid_2, we should get empty return because there is no positional parameters.

also, I got the return from the 2nd for loop.

$mid_1 $freq_1 $mid_2 $freq_2 $mid_3 $freq_3 $mid_4 $freq_4

this is wrong, it should be empty. How do I define variables in this condition and echo each value of the variable? Please advise, thanks.


Solution

  • Don't use variables like mid_1, mid_2, etc. Use an array.

    mid=()
    freq=()
    while (( $# >= 2 )); do
        mid+=("$1")
        freq+=("$2")
        shift 2
    

    Now you can use ${mid[0]}, ${freq[0]}, ${mid[1]}, ${freq[1]} and so on.