Bash Script to let user choose from a list or enter their own

核能气质少年 提交于 2021-02-05 08:49:27

问题


I have a simple script which i want to list some pre-filled choices or for the user to enter a number to correlate with a build

This is what I have currently.

read -p "Please select from the list below or enter the build number you would like to download " build
    case {build} in
        Latest)
            build=lastSuccessful
            break;;
        *)
            break;;
    esac

The problem is that is doesn't provide a list for the user to choose.

Ideally it would look something like this

Build Choices 1) Latest 3) Successful 5) pick a build number (1-10000) 2) Stable 4) etc. Please select from the list above or enter the build number you would like to download: _

Or would it be better to do this in 2 case statements? Asking if they want to choose a particular build or enter their own.

UPDATE: After some thinking I ended up simplifying it to a yes no statement

while true;do
    read -p "Would you like to download the latest successful build? (yes/no) " yn
    case $yn in
        [Yy]*)
            echo
            build=lastSuccessfulBuild
            break;;
        [Nn]*)
            echo
            read -p "Enter the build number to download: " build
            break;;
        *) echo 'I am not going to tell you again';;
        [Qq]*) exit 0;;
    esac
done

回答1:


A select statement might be what you want:

select name in Latest Successful  Stable "Pick a Build Number" ;
do
  case "$name" in
        Latest)
            build=lastSuccessful
            break
          ;;
        Successful)
            build=lastSuccessful
            break
          ;;
        Stable)
            build=lastSuccessful
            break
            ;;
        Pick*)
            read -p "Enter a number from 1 to 10000: " number
            break
            ;;
  esac
done

This generates the menu:

1) Latest
2) Successful
3) Stable
4) Pick a Build Number
#?

The user can enter 1, 2, or 3 and the variable name is set to the corresponding string.




回答2:


You may like dialog as well.

Chceck this out:

dialog --no-cancel --menu "Please select from the list below or enter the build number you would like to download " 11 60 12 1 Latest 2 Successful 3 Stable


来源:https://stackoverflow.com/questions/28420705/bash-script-to-let-user-choose-from-a-list-or-enter-their-own

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!