kcmallard
kcmallard

Reputation: 197

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. 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):

#!/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;

Upvotes: 0

Views: 4193

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74695

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 [. 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. If myCracker == myCombo is ever true, myCracker won't be incremented so the loop will never terminate. The break statement deals with this.

I left the else branch in deliberately to show the syntax but you could also remove it entirely:

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.

Upvotes: 2

JustArchi
JustArchi

Reputation: 129

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

Upvotes: 1

Related Questions