1

我试图用数组来模拟 C 枚举语义,但没有太多成功,基本上我希望能够遍历一组项目,并且只使用这样的标识符来声明一个变量:

$ bash -version
GNU bash, versión 4.1.10(4)-release (i686-pc-cygwin)

糟糕的尝试:

    #!/bin/bash
    STATES=(INITIAL DEFAULT_CS_SETUP  CREATED_CS CHECKED_OUT_DIR MKELEMENT_FILE\
CREATED_BRANCH CHECKED_IN_DIR COMPLETE)
    tam=${#STATES[@]}
    dereference()
    {
       tam=${#STATES[@]}
       for ((j=0; j < $tam; j++)); do
          if [[ "$state" == ${STATES[j]} ]];then
           echo $j
           break
         fi
       done
    }

    echo get the INITIAL state
    state=INITIAL
    echo ${STATES[`dereference`]}

    echo get the next state from CREATED_CS
    state=CREATED_CS
    echo ${STATES[`dereference`+1]}

    echo list elements from CREATED_CS to the end
    state=CREATED_CS
    for ((i=`dereference`; i < $tam; i++)); do
      echo ${STATES[$i]}
    done

    echo list elements from CREATED_CS to CREATED_BRANCH is really awkward
    state=CREATED_BRANCH
    tmp_ind=`dereference`
    state=CREATED_CS
    for ((i=`dereference`; i <= $tmp_ind; i++)); do
      echo ${STATES[$i]}
    done

输出:

get the INITIAL state
INITIAL
get the next state from CREATED_CS
CHECKED_OUT_DIR
list elements from CREATED_CS to the end
CREATED_CS
CHECKED_OUT_DIR
MKELEMENT_FILE
CREATED_BRANCH
CHECKED_IN_DIR
COMPLETE
list elements from CREATED_CS to CREATED_BRANCH is really awkward
CREATED_CS
CHECKED_OUT_DIR
MKELEMENT_FILE
CREATED_BRANCH

最根本的问题不是关于上述代码的正确性,而是我有一个带有状态和转换的脚本,我不想通过索引来记住每个状态,我想使用标签来代替。

谢谢!

4

1 回答 1

3

如果您对在这里和那里使用一些符号感到满意,$那么声明一些常量怎么样:

#!/bin/bash

STATES=(INITIAL DEFAULT_CS_SETUP CREATED_CS CHECKED_OUT_DIR MKELEMENT_FILE CREATED_BRANCH CHECKED_IN_DIR COMPLETE)
tam=${#STATES[@]}
for ((i=0; i < $tam; i++)); do
    name=${STATES[i]}
    declare -r ${name}=$i
done

echo get the INITIAL state
echo ${STATES[$INITIAL]}

echo get the next state from CREATED_CS
echo ${STATES[$CREATED_CS+1]}

echo list elements from CREATED_CS to the end
for ((i=$CREATED_CS; i < $tam; i++)); do
    echo ${STATES[$i]}
done

echo list elements from CREATED_CS to CREATED_BRANCH
for ((i=$CREATED_CS; i <= $CREATED_BRANCH; i++)); do
    echo ${STATES[$i]}
done
于 2013-06-19T15:40:19.447 回答