【BASH】如何从选项列表中选择

本文介绍了一种使用Bash脚本中的select命令来创建交互式目录选择列表的方法。这种方法允许用户仅在必要时从提供的列表中进行选择,提高了用户体验。通过一个具体的示例,展示了如何设置选项列表及处理用户的输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 


 

问题

如何提供给用户选项列表,并且只有在必要的时候,用户才需要进行选择

 

解决方案

使用bash内置的select命令来创建选项列表,用户通过对应的序号进行选择。

#!/bin/bash

# cookbook filename: select_dir
directorylist="Finished $(ls /)"
PS3='Directory to process? ' # Set a useful select prompt
until [ "$directory" == "Finished" ]; do
printf "%b" "/a/n/nSelect a directory to process:/n" >&2
select directory in $directorylist; do
# User types a number which is stored in $REPLY, but select
# returns the value of the entry
if [ "$directory" = "Finished" ]; then
echo "Finished processing directories."
break
elif [ -n "$directory" ]; then
echo "You chose number $REPLY, processing $direc"
# Do something here
break
else
echo "Invalid selection!"
fi
# end of handle user's selection
done # end of select a directory
done # end of while not finished

讨论

通过上面的示例可以看出,select使得创建一个选项列表更加简单,不过值得注意的一点是要提供一个退出或是完成的选项。

用户的选择序号保存在$REPLY中,选择的值保存在调用select时候你指定的变量中。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值