Search code examples
bashshellsh

Shell Bash: How to prompt a user to select from a dynamically populated list?


newbie here!

On a Shell Script (bash), after prompting user for name/password the script should read from a server.list and generate option for selection.

How do I provide the user the options from server.list like so:

#Please select from the server list:  

1) 10.1.1.xx

2) 10.1.1.xx

3) 10.1.1.xx

Select option [1]:  

Any help would be appreciated!


Solution

  • Supposing this source file:

    $ cat server.list 
    10.1.1.xx
    10.1.2.xx
    10.1.3.xx
    

    Short answer:

    select ip in $(cat server.list); do 
       echo $REPLY $ip
    done
    

    Demo

    $ select ip in $(cat server.list); do echo $REPLY $ip; done
    1) 10.1.1.xx
    2) 10.1.2.xx
    3) 10.1.3.xx
    #? 1
    1 10.1.1.xx
    #? 2
    2 10.1.2.xx
    

    You will have to implement a case loop to do something useful with the ip variable.

    Example

    select ip in $(cat server.list) exit; do 
       case $ip in
          exit) echo "exiting"
                break ;;
             *) echo ip $ip;
       esac
    done