Bash – Why would I get integer expression expected

bashshell-scripttest

So, I'm trying to create a menu system in bash as a learning experience. I'm sure there are countless ways, and even "better" ways to do this, but what I've got is something like this…

echo "
2nd Menu
********
1) command
2) command
M) Main menu
X) Exit program
"
read -p "Choose option >" opt
if [ "$opt" -eq 1 ]; then
    commands
elif [ "$opt" -eq 2 ]; then
    commands
elif [[ "$opt" = [m,M] ]]; then
    main #calls the function main()
elif [[ "$opt" = [x,X] ]]; then
    exit
else
    echo "Invalid option"
    main
fi

The script works for every option except the "X) Exit program".
When I run "X" or "x" I get this error…

./acct-mgr.sh: line 10: [: x: integer expression expected
./acct-mgr.sh: line 12: [: x: integer expression expected
Invalid option

This is baffling me! I'm pretty sure I'm using the correct comparison operator for each data type (-eq for integers and = for strings), coupled with the fact that EVERY option works EXCEPT that "x".

Any help is greatly appreciated. Thanks.

P.S. – Alternative ways of accomplishing the desired result is greatly appreciated, but even then I would like to know why this isn't working for my edification. Thanks again.

Best Answer

When you enter M/m or X/x, you're comparing a non-number to a number using -eq, and that is causing the failure. If you want $opt to be a string sometimes, treat it as a string all of the time:

...
if [ "$opt" = "1" ]; then
    commands
elif [ "$opt" = "2" ]; then
    commands
...
Related Question