taine
taine

Reputation: 15

How can i loop my bash if statment until it meets the requirement

The code works if you do bash launch_script.sh 5 6 but if i do bash launch_script.sh 6 5 it asks for new start value but it doesn't use it in the script - the script just ends.

#!/bin/bash
a=$1
b=$2
if [ $1 -gt $2 ]
then 
    echo "$1 is bigger then $2, plz input new start number"
    read -p "You're start number will be?: "
else
    until [ $a -gt $b ];
    do
        echo $a
        ((a++))
    done
fi

Upvotes: 0

Views: 54

Answers (1)

choroba
choroba

Reputation: 241928

The loop is not executed, because it's part of the else block. If you want to run the loop always, put it after the end of the if:

#!/bin/bash
a=$1
b=$2
if (( $1 > $2 )) ; then 
    echo "$1 is bigger then $2, plz input new start number"
    read -p "You're start number will be?: " a
fi

until (( $a > $b )) ; do
    echo $((a++))
done

To loop over the read statement, just introduce a similar loop:

#!/bin/bash
a=$1
b=$2
while (( $a > $b )) ; do
    echo "$1 is bigger then $2, plz input new start number"
    read -p "You're start number will be?: " a
done

until (( $a > $b )) ; do
    echo $((a++))
done

Note that I fixed several issues in your code:

  • read can assign the value directly to a variable.
  • Code should be indented for readability.
  • I also used the (( arithmetic condition )) syntax which is easier to understand, and included the increment to the echo.

Upvotes: 1

Related Questions