这是我正在为我的 Linux 课程编写的脚本。我想添加一个 while 循环来重新运行 case 语句=。任何帮助将不胜感激。这是我的脚本
#!/bin/bash
DATE=$(date -d "$1" +"%m_%d_%Y");
clear
echo -n " Have you finished everything?"
read response
if [ $response = "Y" ] || [ $response = "y" ]; then
echo "Do you want a cookie?"
exit
elif [ $response = "N" ] || [ $response = "n" ]; then
echo "1 - Update Linux debs"
echo "2 - Upgrade Linux"
echo "3 - Backup your Home directory"
read answer
case $answer in
1) echo "Updating!"
sudo apt-get update;;
2) echo "Upgrading!"
sudo apt-get upgrade;;
3) echo "Backing up!"
tar -cvf backup_on_$DATE.tar /home;;
esac
echo "Would you like to choose another option?"
read condition
fi
答案1
while true; do
#your code
#break to break the infinite loop
break
done
答案2
我知道您正在为一堂课这样做,而且我知道最近有人谈论不仅仅是给出纯粹的答案,而是尝试帮助引导用户自己发现正确的答案。这通常是通过问题形式的评论来完成的(又名苏格拉底方法)。我发现这种方法有点过于迂回,因为答案应该只是——一个答案——和一个满的答案不够模糊,不会让刚接触问题的用户感到困惑。
如果您正在寻找一种专门重复使用您的case
语句的方法,那么这不是您的答案。但是,如果您愿意使用纯if/else
逻辑和一些方法以另一种方法来解决此问题functions
,那么我建议这样做:
#!/bin/bash
# try to refrain from setting variables in all-caps,
# which could possibly override default shell environment variables
# not exactly sure why you're passing an argument to date here,
# but that's beside the point. For my own purposes, I will comment it out
# and just make the variable of today's date
# DATE="$(date -d "$1" +"%m_%d_%Y")"
date="$(date +%m_%d_%Y)"
clear
# read -p prompts for user input and then sets the response as a variable
read -p "Have you finished everything? [y/n] " response
# with single brackets, you can use the -o flag to represent "or"
# without having to include additional conditional brackets
if [ "$response" = "Y" -o "$response" = "y" ]; then
echo "Do you want a cookie?"
exit
elif [ "$response" = "N" -o "$response" = "n" ]; then
echo "1 - Updadate Linux Debs"
echo "2 - Upgrade Linux"
echo "3 - Backup your Home directory"
else
echo error.
exit
fi
do_stuff() {
read -p "Choose an option: [1-3] " answer
if [[ $answer = 1 ]]; then
echo "Updating!"
sudo apt-get update
elif [[ $answer = 2 ]]; then
echo "Upgrading!"
sudo apt-get upgrade
elif [[ $answer = 3 ]]; then
echo "Backing up!"
tar -cvf "backup_on_${date}.tar" /home
else
echo error.
exit
fi
do_again
}
do_again() {
read -p "Would you like to choose another option? [y/n] " condition
if [ "$condition" = "y" -o "$condition" = "Y" ]; then
do_stuff
else
echo goodbye.
exit
fi
}
do_stuff