bash select menu get index

example

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

So if the user enters 1, the case statement checks for the match on the text, how can I match on 1 instead?


You don't need to check which value is selected; you can simply use it. The only thing you do want to check against is master , which is simple to do.

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

I am struggling to understand your question but here is some example code; the array could be dynamically populated which I guess is where you are coming from:

$ 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

How is this insufficient?

Of course, you could also use read and build the functionality yourself if you want the output/logics to differ from what select offers.

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

上一篇: Shell用户提示(Y / n)

下一篇: bash选择菜单获取索引