0

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
spectre007
  • 1,489
  • 11
  • 18

2 Answers2

6

<= 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

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
  • When I change it to that I get another error: line 3: [: : integer expression expected – user3495658 Sep 24 '15 at 20:07
  • 4
    You've never declared `option` leading up to that point. You're comparing "blank" to a number. Define `option` to some default value like zero. – Mr. Llama Sep 24 '15 at 20:09
  • http://stackoverflow.com/questions/24108548/error-in-two-scripts-unary-operator-expected-and-integer-expression-expected – surya singh Sep 24 '15 at 20:13
3

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
chepner
  • 497,756
  • 71
  • 530
  • 681