首页 > 解决方案 > 需要创建一个循环菜单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

老实说,我只是不确定该怎么做才能让它循环。提前致谢!

标签: bashloopswhile-loop

解决方案


稍微调整了你的代码。将选项的打印和选项的选择放在单独的功能中。添加了一个循环来检查非数字或大于 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

推荐阅读