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.
1) Syntax:Syntax of for loop using in and list of values is shown below. This for loop contains a number of variables in the list and will execute for each item in the list. For example, if there are 10 variables in the list, then loop will execute ten times and value will be stored in varname.
Details. Use == operator with bash if statement to check if two strings are equal. You can also use != to check if two string are not equal.
The word unary is basically synonymous with “single.” In the context of mathematics, this could be a single number or other component of an equation. So, when Bash says that it is expecting a unary operator, it is just saying that you are missing a number in the script.
To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
You can use this syntax:
#!/bin/bash
echo " Write in your age: "
read age
if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
echo " You have to pay for ticket "
fi
If you are using -o
(or -a
), it needs to be inside the brackets of the test
command:
if [ "$age" -le "7" -o "$age" -ge " 65" ]
However, their use is deprecated, and you should use separate test
commands joined by ||
(or &&
) instead:
if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With