user3495658
user3495658

Reputation: 13

Bash - While Loop

I am having trouble with this while loop. Here is the error I am getting currently : [: : unary operator expected (on line 3)

Here is my code:

    #!/bin/bash

while [ "$option" <= 3 ]; do
    echo "1) View 'HelloWorld' Text";
    echo "2) View 'MyName' Text";
    echo "3) View 'HappyFall' Text";
    echo "4) Exit\n";

    read -p "Please choose your option using numbers 1-4: " option;
        if [ "$option" == 1 ]
        then
            cat HelloWorld
        elif [ "$option" == 2 ]
        then
            cat MyName
        elif [ "$option" == 3 ]
        then
            cat HappyFall
        else
        echo "Exiting...";
        fi
done

Upvotes: 0

Views: 388

Answers (2)

Mr. Llama
Mr. Llama

Reputation: 20919

<= is not a valid comparison in bash scripting, but -le (less than or equal) is.

There are two different types of comparison in scripting: those for strings, and those for numbers.

Stings typically use == or != for equal or not equal.
Integers, however, use:

  • -eq equal
  • -ne not equal
  • -lt less than
  • -le less than or equal
  • -gt greater than
  • -ge greater than or equal

Here's a more comprehensive list:
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Blocks_.28if.2C_test_and_.5B.5B.29

Upvotes: 6

chepner
chepner

Reputation: 532418

Error aside, this is a good use case for the select command:

options=(
    "View 'HelloWorld' Text"
    "View 'MyName' Text"
    "View 'HappyFall' Text"
    "Exit"
)
select option in "${options[@]}"; do
    case $REPLY in
        1) cat HelloWorld ;;
        2) cat MyName ;;
        3) cat HappyFall ;;
        *) break ;;
esac
done

Upvotes: 3

Related Questions