问题
如何提供给用户选项列表,并且只有在必要的时候,用户才需要进行选择
解决方案
使用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时候你指定的变量中。
本文介绍了一种使用Bash脚本中的select命令来创建交互式目录选择列表的方法。这种方法允许用户仅在必要时从提供的列表中进行选择,提高了用户体验。通过一个具体的示例,展示了如何设置选项列表及处理用户的输入。
1627

被折叠的 条评论
为什么被折叠?



