bash - 需要创建一个循环菜单shell脚本,不知道如何让它循环
问题描述
到目前为止,我已经能够让我的脚本运行,但还没有弄清楚如何让它循环。有人可以帮我吗?我将发布到目前为止的内容:
#!/bin/bash
#descripton
clear
echo "Please select a menu item"
echo
echo "1) list files in current directory"
echo "2) display block device layout of system"
echo "3) display last 10 lines of /var/log/messages"
echo "4) display RAM info"
echo "5) Display CPU info"
echo "6) exit the program"
echo
read CHOICE
case $CHOICE in
1) ls;;
2) lsblk;;
3) sudo tail -10 /var/log/messages;;
4) free -h;;
5) mpstat -u;;
6) exit;;
*) echo "you have made an invalid selection"
esac
老实说,我只是不确定该怎么做才能让它循环。提前致谢!
解决方案
稍微调整了你的代码。将选项的打印和选项的选择放在单独的功能中。添加了一个循环来检查非数字或大于 6 的选项。它会不断地询问选项,直到给出 1-6 的输入。
#!/bin/bash
#descripton
print_options (){
echo "Please select a menu item"
echo
echo "1) list files in current directory"
echo "2) display block device layout of system"
echo "3) display last 10 lines of /var/log/messages"
echo "4) display RAM info"
echo "5) Display CPU info"
echo "6) exit the program"
echo
}
selection (){
case $CHOICE in
1) ls;;
2) lsblk;;
3) sudo tail -10 /var/log/messages;;
4) free -h;;
5) mpstat -u;;
6) exit;;
*) echo "you have made an invalid selection"
esac
}
print_options
read CHOICE
while [[ $CHOICE =~ [^0-9] || $CHOICE -gt 6 ]]
do
echo "Invalid choice"
print_options
read CHOICE
selection
done
推荐阅读
- scala - Scala 中的隐式函数类型
- javascript - 在获得响应时出现问题,因为获取结果未定义
- amazon-web-services - Boxfuse 在运行期间静默忽略弹性 IP 参数
- python - 在 Django 中创建可重复使用的问题模板
- socket.io - 如何获得所有订阅状态或公共频道的列表?
- r - 还有其他人从 knn.impute 得到这个错误吗?
- javascript - 将旧页面迁移到新站点---出现的数据不会回来
- java - 如何将 application.properties 中的休眠连接字符串包含到 .gitlab-ci.yml
- swift - 如何删除由动态部分组成的 swiftui 列表中的项目?
- c++ - 无法使用 LoadObject() 函数编译 UE4 Actor