简体   繁体   English

在 Bash 脚本中使用 for 循环定义具有位置参数的变量

[英]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?有没有办法在 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.在 bash 中定义,mid_2=$3,并且 echo $mid_2,我们应该得到空返回,因为没有位置参数。

also, I got the return from the 2nd for loop.另外,我从第二个 for 循环中得到了回报。

$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.请指教,谢谢。

Don't use variables like mid_1 , mid_2 , etc. Use an array.不要使用mid_1mid_2等变量。使用数组。

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.现在您可以使用${mid[0]}${freq[0]}${mid[1]}${freq[1]}等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM