简体   繁体   English

如何在Bash Shell脚本的while语句中编写if语句?

[英]How do I write an if statement within a while statement in Bash Shell Script?

I'm currently having simple syntax issues with the following bash shell script. 我目前在以下bash shell脚本中遇到简单的语法问题。 I'm not sure what the syntax is for nesting an if statement into a while statement, or if it's even possible with bash shell scripting (new to all things linux): 我不确定将if语句嵌套到while语句中的语法是什么,或者使用bash shell脚本(对于Linux所有东西都是新的)甚至是不可能的:

#!/bin/bash

myCombo=$((RANDOM%99999+10000));
echo ${myCombo};

myCracker=00000;

while [ (($myCracker<=99999)) ]; do
    if [ $myCracker -eq myCombo ]
    then
        echo "The combination is " ${myCracker} " !"
    else [ $myCracker = $myCracker + 1 ]
    fi
done;

There were quite a few things wrong with your loop. 您的循环有很多错误。 I've made a number of improvements below: 我在下面做了一些改进:

while (( myCracker <= 99999 )); do
    if (( myCracker == myCombo )); then
        echo "The combination is $myCracker !"
        break
    else
        (( ++myCracker ))
    fi
done

As you're using bash, you can make use of (( arithmetic contexts )) , which don't need enclosing in [ . 使用bash时,可以使用(( arithmetic contexts )) ,它不需要包含在[ Within them, variable names are expanded, so do not require prefixing with $ . 在其中,变量名被扩展,因此不需要在$前面加上前缀。

Note that your original logic will either loop indefinitely or never echo , which is probably a bug. 请注意,您的原始逻辑将无限期循环或永不echo ,这可能是一个错误。 If myCracker == myCombo is ever true, myCracker won't be incremented so the loop will never terminate. 如果myCracker == myCombo为true,则myCracker不会递增,因此循环永远不会终止。 The break statement deals with this. break语句处理了这个问题。

I left the else branch in deliberately to show the syntax but you could also remove it entirely: 我故意离开了else分支以显示语法,但是您也可以将其完全删除:

while (( myCracker++ <= 99999 )); do
    if (( myCracker == myCombo )); then
        echo "The combination is $myCracker !"
        break
    fi
done

The break is still useful as it prevents the loop from continuing unnecessarily. break仍然有用,因为它可以防止循环不必要地继续。

You can also use extended tests instead of arithmetic contexts if you do simple comparisions. 如果进行简单的比较,也可以使用扩展测试而不是算术上下文。 They should be a little faster, and are more common. 它们应该更快一点,并且更常见。

while [[ $myCracker -le 99999 ]]; do
    if [[ $myCracker -eq $myCombo ]]; then
        echo "The combination is ${myCracker}!"
        break
    else
        ((myCracker++))
    fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM