条件脚本问题

条件脚本问题

我正在创建一个简单的 bash 脚本

#!/bin/bash
echo "Q:1 What does CD command do? ************"
echo "  1)Change directory "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

read n
case $n in
  1) echo "correct answer";;
  2) echo "Wrong Answer";;
  3) echo "Wrong Answer";;
  4) echo "Wrong Answer";;
  *) echo "invalid option";;
esac

我将通过重复此代码添加 10 到 20 个问题,我想要的是,如果任何一个人给出了错误或正确的答案,他最终会通过说正确答案:?和错误答案:?来获得总分,你的总分是??..如果有人能帮忙的话。谢谢

答案1

您可以设置两个变量,一个用于正确答案计数,另一个用于错误答案计数,初始值为零,然后增加它们。此外,如果插入了无效值,您可能需要使用 while 循环再次请求输入,如下所示:

#!/bin/bash

correct=0
wrong=0

echo "Q:1 What does CD command do? ************"
echo "  1)Change directory "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

while read n

do

case $n in
  1) echo "correct answer"; ((correct++)); break;;
  2) echo "Wrong Answer"; ((wrong++)); break;;
  3) echo "Wrong Answer"; ((wrong++)); break;;
  4) echo "Wrong Answer"; ((wrong++)); break;;
  *) echo "invalid option. Please try again"; ((wrong++));;
esac

done



echo "Q:1 What does SU command do? ************"
echo "  1)Change user "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

while read n

do

case $n in
  1) echo "correct answer"; ((correct++)); break;;
  2) echo "Wrong Answer"; ((wrong++)); break;;
  3) echo "Wrong Answer"; ((wrong++)); break;;
  4) echo "Wrong Answer"; ((wrong++)); break;;
  *) echo "invalid option. Please try again"; ((wrong++));;
esac

done

echo "$correct";
echo "$wrong";

如果提供了输入,将break中断当前的 while 循环并转到下一个问题1,2,3 or 4,否则循环将继续要求输入,直到输入有效的选项ie. 1,2,3, or 4

我想您现在会很容易算出总分。

相关内容