问题
如何提供给用户选项列表,并且只有在必要的时候,用户才需要进行选择
解决方案
使用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时候你指定的变量中。