简体   繁体   English

提示用户从目录列表中选择

[英]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. 这将根据需要生成可用数据集的列表,如果用户选择显示的值,则将数据集文件名放入DATASET目录。

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. 如果用户输入的值不在列表中,那么我编写的select语句将很乐意接受它并继续前进。

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 只需将您的select包入

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

man bash says: man bash说:

If the line consists of the number corresponding to one of the displayed words, then NAME is set to that word. 如果该行由与显示的单词之一相对应的数字组成,则将NAME设置为该单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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