简体   繁体   中英

Prompting user to select from a list of directories

I am writing a script that will download a dataset from a server onto the local host. I want to prompt the user to select the dataset from a list of ones available on the server. So far I have tried the following command

select DATASET in $(ssh -i ssh_key user@server "ls -1 /path/to/datasets/"); do break; done
1) dataset01
2) test1
3) test2
#?

This produces the list of available datasets as I wanted and puts the dataset filename into the DATASET directory if the user selects a value that is displayed.

However this does not do any validation on the selected entry. If a user enters a value that is not in the list, the select statement I wrote will gladly accept it and move forward.

How can I adapt this command to check if the selected value is within the range of options presented?

You can break only if dataset is not empty, like

PS3="Enter number or 0 for exit> "    #better prompt for the select
values=($(seq -f "set%g" 20))  #simulating 20 datasets 
select dataset in "${values[@]}"
do
    [[ "$dataset" ]] && break  #existing dataset selected, break
    (( "${REPLY}" == 0 )) && exit #0 - exit the script
done
echo =$dataset=

Just wrap your select into

DATASET=
while [[ ! $DATASET ]] ; do
    select DATASET in ...
done

man bash says:

If the line consists of the number corresponding to one of the displayed words, then NAME is set to that word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM