Bash块循环索引问题

Bash块循环索引问题,bash,loops,Bash,Loops,我希望以4的增量迭代bash数组。它在第一次迭代中起作用,但在第二次迭代中,元素位置3被映射到元素位置7 如有任何想法/建议,将不胜感激 这是代码- #!/bin/bash # Run as - /tmp/dns.sh qa aqa api envType=$1 clusterType=$2 projectName=$3 declare -a dnsAry if [[ "${envType}" =~ "ci" ]]; then dnsAry+=("dev

我希望以4的增量迭代bash数组。它在第一次迭代中起作用,但在第二次迭代中,元素位置3被映射到元素位置7

如有任何想法/建议,将不胜感激

这是代码-

#!/bin/bash 
# Run as - /tmp/dns.sh qa aqa api

envType=$1      
clusterType=$2   
projectName=$3   

declare -a dnsAry

if [[ "${envType}" =~ "ci" ]]; then

    dnsAry+=("dev.example.com")
    dnsAry+=("${envType}-${projectName}")
    dnsAry+=("${clusterType}-${projectName}")
    dnsAry+=("${envType}-${projectName}-app-and-web-dns")
fi

if [[ "${envType}" =~ "qa" ]]; then

    dnsAry+=("dev.example.com")
    dnsAry+=("${envType}-${projectName}")
    dnsAry+=("${clusterType}-${projectName}")
    dnsAry+=("${envType}-${projectName}-app-dns")

    dnsAry+=("qa.example.com")
    dnsAry+=("${envType}-${projectName}")
    dnsAry+=("${clusterType}-${projectName}")
    dnsAry+=("${envType}-${projectName}-web-dns")
fi

echo -e "Array size : ${#dnsAry[@]}"
echo -e "Array content : ${dnsAry[@]}"

for (( j = 0; j < "${#dnsAry[@]}"; j+=4 )) do
    echo -e "Loop content $(( $j )) : ${dnsAry[${j}]}"  
    echo -e "Loop content $(( $j + 1)) : ${dnsAry[${j+1}]}" 
    echo -e "Loop content $(( $j + 2)) : ${dnsAry[${j+2}]}" 
    echo -e "Loop content $(( $j + 3)) : ${dnsAry[${j+3}]}" 
done
预期输出应为-注意元素7

/tmp/dns.sh qa aqa hapi

Array size : 8
Array content : dev.example.com qa-hapi aqa-hapi qa-hapi-app-dns qa.example.com qa-hapi aqa-hapi qa-hapi-web-dns
Loop content 0 : dev.example.com
Loop content 1 : qa-hapi
Loop content 2 : aqa-hapi
Loop content 3 : qa-hapi-app-dns
Loop content 4 : qa.example.com
Loop content 5 : qa-hapi
Loop content 6 : aqa-hapi
Loop content 7 : qa-hapi-web-dns

这不是很明显吗?访问数组索引的方式是错误的!语法
{var+1}
不是
bash
中算术增量的正确语法,您需要有
((var+1))



或者更简单地说,只是避免为此引入运行参数扩展的范围,只使用
${dnsAry[j+1]}
,而不使用为索引引入的
${..}

我觉得这很好。你期望的结果是什么?
/tmp/dns.sh qa aqa hapi

Array size : 8
Array content : dev.example.com qa-hapi aqa-hapi qa-hapi-app-dns qa.example.com qa-hapi aqa-hapi qa-hapi-web-dns
Loop content 0 : dev.example.com
Loop content 1 : qa-hapi
Loop content 2 : aqa-hapi
Loop content 3 : qa-hapi-app-dns
Loop content 4 : qa.example.com
Loop content 5 : qa-hapi
Loop content 6 : aqa-hapi
Loop content 7 : qa-hapi-web-dns
for (( j = 0; j < "${#dnsAry[@]}"; j+=4 )) do
    echo -e "Loop content $(( $j )) : ${dnsAry[${j}]}"
    echo -e "Loop content $(( $j + 1)) : ${dnsAry[$((j+1))]}"
    echo -e "Loop content $(( $j + 2)) : ${dnsAry[$((j+2))]}"
    echo -e "Loop content $(( $j + 3)) : ${dnsAry[$((j+3))]}"
done
# foo="" 
foo="something"

if [[ ${foo+isset} = isset ]]; then
  echo "foo is set..."
else
  echo "foo is not set..."
fi