bash选择菜单获取索引

#!/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?


您不需要检查选择了哪个值; 你可以简单地使用它。 你唯一想检查的是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

使用$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

我很努力地理解你的问题,但这里是一些示例代码; 该数组可以动态填充,我猜你是从哪里来的:

$ 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

这是如何不足?

当然,如果您希望输出/逻辑与select不同,您也可以使用自己的read和构建功能。

链接地址: http://www.djcxy.com/p/25547.html

上一篇: bash select menu get index

下一篇: Handling input confirmations in Linux shell scripting