字符数组上的 for 循环给出意外的“(”

字符数组上的 for 循环给出意外的“(”

我是 Bash 脚本的新手,如果下面的内容非常简单,我很抱歉。我得到的错误是:

4: Syntax error: "(" unexpected

我基本上是尝试在 Ubuntu 10.04.4 LTS 服务器上的 bash 中运行以下命令:

#!/bin/bash

### Positions
declare -a POS=("01" "02" "03" "04" "05" "06" "16" "17" "18")

### Timeslices
declare -a ZSPOS_01=("1" "3" "4" "5")
declare -a ZSPOS_02=("1" "2" "3" "4" "5" "6" "8" "9" "10" "11" "12" "31" "41" "51" "101")
declare -a ZSPOS_03=("1" "2" "3" "4" "5" "6" "7" "8" "9" "31" "41" "91")
declare -a ZSPOS_04=("1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "41" "51" "101")
declare -a ZSPOS_05=("2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "51" "61" "101")
declare -a ZSPOS_06=("1" "2" "3" "4" "5" "6" "7" "8" "31" "51" "71")
declare -a ZSPOS_16=("1" "2" "3" "4" "11" "41")
declare -a ZSPOS_17=("1" "2" "3" "4" "11" "41")
declare -a ZSPOS_18=("1" "2" "3" "4")

for SCANPOSITION in ${POS[@]}
do
    for ZEITSCHNITT in ${ZSPOS_$SCANPOSITION[@]}
        do
            echo "Timeslice" $ZEITSCHNITT "in Position" $SCANPOSITION "!"
        done
done

答案1

  1. ( unexpected错误表明您正在调用脚本sh scriptname而不是bash scriptname或者最好是chmod 755 scriptname; ./scriptname

  2. 在 Bash 中,动态数组名称很难使用。您需要一个临时变量来使用间接扩张

    for SCANPOSITION in "${POS[@]}"
    do
        tmp="ZSPOS_${SCANPOSITION}[@]"
    
        for ZEITSCHNITT in "${!tmp}"    # note the "!"
        do
            echo "Timeslice $ZEITSCHNITT in Position $SCANPOSITION !"
        done
    done
    
  3. 您应该始终引用您的内容,"$variables"除非您确切知道为什么要省略引号。

  4. 另外,要改掉使用习惯ALL_CAPS_VARS——总有一天你会意外使用PATH然后想知道为什么你的脚本坏了

相关内容