简体   繁体   English

带有 Shell 脚本的数组中的“如果”

[英]'if' in array w/ Shell Script

I have an array with different values, and if the value is 3 (integer) this value will be exchanged for 999 (integer).我有一个具有不同值的数组,如果值为 3(整数),则此值将交换为 999(整数)。 But I have a syntax problem in the 'if' block of the array.但是我在数组的“if”块中有一个语法问题。

The correct return would be: 1 999 5 7 9 999正确的回报是:1 999 5 7 9 999

vetor=(1 3 5 7 9 3)
for i in ${vetor[*]}
do
    if [[ ${vetor[i]} = 3 ]]; then
        ${vetor[i]} = 999
    fi
    echo $i
done

This produces the correct output in Bash:这会在 Bash 中生成正确的 output:

vetor=(1 3 5 7 9 3);
for i in ${!vetor[*]};
do
     if [[ ${vetor[i]} -eq 3 ]]; then
         vetor[i]=999;
     fi;
     echo ${vetor[i]};
done

I added !我加了! in the for loop expression to get the indices of vetor instead of the values, and I removed the ${} around the assignment in the if condition (this was giving "if 3 is not a typo" warnings).在 for 循环表达式中获取vetor的索引而不是值,并且我在 if 条件中删除了赋值周围的 ${} (这给出了“如果 3 不是错字”警告)。 Also changed the echo to get the value at vetor[i] instead of printing the index.还更改了 echo 以获取 vetor[i] 的值,而不是打印索引。

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

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