【问题标题】:logic errors in scripts脚本中的逻辑错误
【发布时间】:2020-09-08 19:51:55
【问题描述】:
#!/bin/bash
whilenum=1
while [ $whilenum -lt 5 ]
do 

if  [ $whilenum == 1 ]
then
function funct1 {
echo The value of whilenum is $whilenum
}
funct1 
else break
fi

if (( $whilenum == 2 | $whilenum == 3 ))
then
for animal in dog bird turtle
do
echo $animal
done
fi  

if [ $whilenum == 4 ]
then
echo Enter your name
read username
fi

if [ ${#username} >  8 ]
then
echo User name is long
else
echo User name is short

fi

whilenum=$(( $whilenum+1 ))
done 

当我调整数字以测试数字时,没有任何反应 我使while循环递增,因此它可以终止但不确定它是否工作。没有得到任何语法错误可能有一些逻辑错误

【问题讨论】:

    标签: linux bash for-loop while-loop do-while


    【解决方案1】:

    问题是如果 whilenum 不等于 1,您将中断。因此,您的脚本将无法继续。我认为您应该删除else break,您应该能够发现它有效。

    【讨论】:

      【解决方案2】:

      语法有效,但您缺少一些东西,因为您没有缩进代码。
      whilenum -eq 1${#username} 在每个循环中被检查时,中断就完成了。
      请注意if [ $whilenum == 1 ] 查找字符串"1",使用-eqif (( $whilenum == 1 ))

      您确实尝试过编写代码和学习,所以我希望您能学习下面的代码。 可以使用 for-loopcase 语句改进您的代码:

      function funct1 {
         echo The value of whilenum is $whilenum
      }
      
      for (( whilenum=1; whilenum < 5; whilenum++ )); do
         case $whilenum in
         1)
            funct1
         ;;
         [23])
            for animal in dog bird turtle
            do
               echo $animal
            done
         ;;
         4)
            read -p "Enter your name: " username
            if [ ${#username} -gt  8 ] # or use if (( ${#username} > 8 ))
            then
               echo User name is long
            else
               echo User name is short
            fi
         ;;
         *)
            echo "The default will not be reached. Put an echo here for when someone changes the for-loop conditions."
         ;;
         esac
      done
      

      【讨论】:

      • 非常感谢学习目的我必须使用一个while循环来检查while num是否等于5并在底部增加。将在使用 while 循环时应用 case 语句,看看会发生什么:)
      • 如果一个case语句是一个条件语句?
      • case $var in something) 检查if [ "$var" = something ],这是写 `if-then-else if-else if-- else-if 的简写方式。所以是的,这是一种条件语句。
      猜你喜欢
      • 1970-01-01
      • 2011-04-26
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多