I'm a newbie to shell scripts so I have a question. What Im doing wrong in this code?
#!/bin/bash
echo " Write in your age: "
read age
if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
then
echo " You can walk in for free "
elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
then
echo " You have to pay for ticket "
fi
When I'm trying to open this script it asks me for my age and then it says
./bilet.sh: line 6: [: 7]: integer expression expected
./bilet.sh: line 9: [: missing `]'
I don't have any idea what I'm doing wrong. If someone could tell me how to fix it I would be thankful, sorry for my poor English I hope you guys can understand me.
Try this:
You can use this syntax:
If you are using
-o
(or-a
), it needs to be inside the brackets of thetest
command:However, their use is deprecated, and you should use separate
test
commands joined by||
(or&&
) instead:Make sure the closing brackets are preceded with whitespace, as they are technically arguments to
[
, not simply syntax.In
bash
and some other shells, you can use the superior[[
expression as shown in kamituel's answer. The above will work in any POSIX-compliant shell.This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.
For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like
"\n"
or"\r"
.For example:
This will result in a script error
: integer expression expected
because$a
contains a non-digit newline character"\n"
. You have to remove this character using the instructions here: How to remove carriage return from a string in BashSo use something like this:
You can also use
set -xv
to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/Be careful with
" "
This is because you need to have space between brackets like:
look: added space, and no
" "