我正在试图弄清楚如何在bash中创建一个while-do-done脚本,这将允许我选择选项1-4,如果我使用1-4将允许我再次选择按'n '退出或任何键继续。感谢您的任何意见,我非常感谢。
#!/bin/bash
#while-do-done
RED='\033[0;31m'
NC='\033[0m'
#options 1-4 have options, option 5-x is else command
echo "Type one of the following:"
echo "1 - whoami"
echo "2 - df"
echo "3 - date"
echo "4 - cal"
echo -n "select option:"
read option
while [ $option == "1" ]
whoami
echo "Enter another command?"
echo "Press 'n' to exit. Any key to continue"
if [ $option == "n" ]
then exit
fi
while [ $option == "2" ]
df
while [ $option == "3" ]
date
while [ $option == "4" ]
cal
while [ $option == * ]
printf "${RED} You made an invalid selection. Exiting.${NC}"
exit 0
答案 0 :(得分:0)
我认为这就是你所追求的目标。
#!/usr/bin/env bash
RED='\033[0;31m'
NC='\033[0m'
showmenu() {
echo "Type one of the following:"
echo " 1 - whoami"
echo " 2 - df"
echo " 3 - date"
echo " 4 - cal"
}
# Your loop starts here.
while true; do
showmenu # This calls the function above.
read -p "Enter selection: " option
case "$option" in
1) whoami ;;
2) df ;;
3) date ;;
4) cal ;;
*)
echo "${RED}Invalid selection. Exiting.${NC}"
break # Quit the loop, resuming execution after "done"
;;
esac
read -p "Enter another command (y/n)?" cont
case "$cont" in
N*|n*) break ;; # Quit the loop, resuming execution after "done"
*) continue ;; # Restart the loop. Not strictly necessary here,
# since there's nothing left to skip before "done".
esac
done
echo "I quit."
顺便说一下,这个脚本大部分都不需要bash;您可以在大多数系统上使用/bin/sh
运行它。