Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer expression expected error in shell script

Tags:

bash

shell

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.

like image 411
user2904832 Avatar asked Oct 21 '13 21:10

user2904832


People also ask

How do you write a loop in shell script?

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.

How do I check if two strings are equal in Linux?

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.

What is unary operator in shell scripting?

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.

Is variable empty bash?

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"


2 Answers

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
like image 100
kamituel Avatar answered Oct 06 '22 22:10

kamituel


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.

like image 15
chepner Avatar answered Oct 06 '22 22:10

chepner