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
1
  • I might need to mention that the error is in line 3 (while [ "$option" <= 3 ]; do) Commented Sep 24, 2015 at 20:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

When I change it to that I get another error: line 3: [: : integer expression expected
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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.