bash选择菜单获取索引

时间:2014-03-28 13:25:33

标签: bash shell select

例如

#!/bin/bash

INSTALL_PATH="/usr/local"
BFGMINER_INSTALL_PATH="${INSTALL_PATH}/bfgminer"
BFGMINER_REPO="https://github.com/luke-jr/bfgminer.git"

list_last_ten_bfgminer_tags () {
    cd ${BFGMINER_INSTALL_PATH}
    git for-each-ref --format="%(refname)" --sort=-taggerdate --count=10 refs/tags | cut -c 6-
}

clone_bfgminer () {
    cd ${INSTALL_PATH}
    git clone ${BFGMINER_REPO} ${BFGMINER_INSTALL_PATH}
}

echo "select number to switch tag or n to continue"
select result in master $(list_last_ten_bfgminer_tags)
do

    # HOW DO I CHECK THE INDEX???????  <================================= QUESTION
    if [[ ${result} == [0-9] && ${result} < 11 && ${result} > 0 ]]
        then
            echo "switching to tag ${result}"
            cd ${BFGMINER_INSTALL_PATH}
            git checkout ${result}
    else
        echo "continue installing master"
    fi

    break
done

因此,如果用户输入1,则case语句会检查文本上的匹配项,如何在1上匹配?

3 个答案:

答案 0 :(得分:12)

使用$REPLY变量

PS3="Select what you want>"
select answer in "aaa" "bbb" "ccc" "exit program"
do
case "$REPLY" in
    1) echo "1" ; break;;
    2) echo "2" ; break;;
    3) echo "3" ; break;;
    4) exit ;;
esac
done

答案 1 :(得分:6)

您不需要检查选择了哪个值;你可以简单地使用它。你唯一想要检查的是master,这很容易做到。

select result in master $(list_last_ten_bfgminer_tags)
do
    if [[ $result = master ]]; then
        echo "continue installing master"
    elif [[ -z "$result" ]]; then
        continue
    else
        echo "switching to tag ${result}"
        cd ${BFGMINER_INSTALL_PATH}
        git checkout ${result}
    fi
    break
done

答案 2 :(得分:4)

我很难理解你的问题,但这里有一些示例代码;数组可以动态填充,我想你来自哪里:

$ cat t.sh
#!/bin/bash

foo=(one two three four)

echo "Please select an option: "
select reply in "${foo[@]}"; do
        [ -n "${reply}" ] && break
done
echo "You selected: ${reply}"

$ ./t.sh
Please select an option:
1) one
2) two
3) three
4) four
#? 5
#? 100
#? 2
You selected: two

这怎么不够?

当然,如果您希望输出/逻辑与read提供的内容不同,您也可以使用select并自行构建功能。