如何通过在 shell 脚本中选择菜单来定义快捷方式,例如“c”代表“创建”、“d”代表“删除”或“n”代表“新建”?
代码:
#!/bin/bash
PS3="Enter an option: "
select option in create delete new quit
do
echo "Selected option was: $option"
if [ "$option" == "create" ]
then
read -r -p 'Create new partition: Please define a name of the partition: ' new_partition
read -r -p 'Define Size: Please define a size of the partition: ' partition_size
break
fi
if [ "$option" == "delete" ]
then
read -r -p 'Delete partition: Please define a name of the partition: ' delete_partition
break
fi
if [ "$option" == "new" ]
then
read -r -p 'Reset memory usage: Please define a name of the partition: ' reset_partition
break
fi
if [ "$option" == "quit" ]
then
break
fi
done
答案1
您在select
提示中输入的任何内容都将反映在$REPLY
变量中。不幸的是,您必须按“回车”键才能终止输入。因此,$REPLY
无论何时输入“c”、“d”、“n”或“q”字符,都将保留“c”、“d”、“n”或“q”字符,并且您可以case
对其运行语句:
PS3="enter create, delete, new, quit, and hit <Return> "
select OP in create delete new quit
do echo ">$OP<, >$REPLY<"
done
1) create
2) delete
3) new
4) quit
enter create, delete, new, quit, and hit <Return> c
><, >c<
enter create, delete, new, quit, and hit <Return> d
><, >d<
enter create, delete, new, quit, and hit <Return> 1
>create<, >1<
enter create, delete, new, quit, and hit <Return>
答案2
读取输入,然后进行大小写切换:
#!/bin/sh
echo select... c: create, d: delete, x:xxx...
read OPT
case $OPT in
c*)
echo c
;;
d*)
echo d
;;
*)
echo “User Selected Choice not present”
exit 1
esac