【问题标题】:Need to create a looping menu shell script, cant figure out how to make it loop需要创建一个循环菜单shell脚本,不知道如何让它循环
【发布时间】:2021-05-24 08:22:26
【问题描述】:

到目前为止,我已经能够让我的脚本运行,但还没有弄清楚如何让它循环。有人可以帮我吗?我会发布我目前所拥有的:

#!/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

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

【问题讨论】:

  • 这可能会有所帮助:while true; do echo hello; sleep 1; done
  • 我会把它放在哪里?在开始之前在顶部?
  • 网上教程和help bash/help while应该会讲解。
  • @SlothJesus :为了让用户选择一组替代品,select 可能比case 更好,因为它隐含地对不正确的选择进行错误处理。

标签: bash loops while-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-04-06
    • 2021-03-22
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-17
    相关资源
    最近更新 更多