Integer expression expected error in shell script - bash

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.

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.

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:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
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 Bash
So use something like this:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'\t\r\n ']}"
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
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/

./bilet.sh: line 6: [: 7]: integer expression expected
Be careful with " "
./bilet.sh: line 9: [: missing `]'
This is because you need to have space between brackets like:
if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]
look: added space, and no " "

Try this:
If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
Something something \n
else \n
Yes it works for me :) \n

If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.
Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
After: if [ "$age" -le "7" -o "$age" -ge "65" ]
Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

Related

line 14: [: 55.5: integer expression expected --shell error

I'm getting error for line 8,11,14,17 .
the program is
#!/bin/sh
read a
b=$(grep -i $a TeamScore.txt| awk 'BEGIN{FS =" "}{print ($2+$4)/2}')
echo "the avg is $b"
if [ "$b" -ge 80] #line8
then
echo "1st class "
elif [ "$b" -lt 80 ] || [ "$b" -ge 70 ] #line11
then
echo "2nd class"
elif [ "$b" -lt 70 ] || [ "$b" -ge 60 ] #line14
then
echo "3rd class"
elif [ "$b" -lt 60 ] #line17
then
echo "fail"
else
echo "code not working"
fi
I'm new to unix and shell scripting and i would like to whats wrong and how can i fix it.the TeamScore.txt contains a table of names and their score(for 2 exams).
The problem is that the test command only understands integers, but you're setting b to 55.5, which contains a fraction. Change the awk command to round it down.
b=$(grep -i $a TeamScore.txt| awk 'BEGIN{FS =" "}{print int(($2+$4)/2)}')
You also need a space before ] on line #8.
Line 8: add an extra space:
if [ "$b" -ge 80 SPACE_HERE_REQUIRED ]
Line11, line14 and line17: number operators can't be compared with strings, so use $b instead of "$b", so, for example, use this
if [ $b -ge 80 ]
instead of:
if [ "$b" -ge 80 ]

Comparing Numbers Two number in bash

I don't know where the problem is: when I execute this, I get an error:
./script.sh: line 4: if[ 7 -gt 5 ]: command not found
./script.sh: line 5: syntax error near unexpected token then'
./script.sh: line 5: `then'
#!/bin/bash
read a
read b
if[ $a -gt $b ]
then
echo "$a is greater than $b"
elif [ $a -lt $b ]
then
echo "$a is less than $b"
else
echo "$a is equal to $b"
fi
The syntax for if in bash follows:
if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Note the space following if; it is mandatory. Note also that [ isn't any kind of special syntax; it's just a command, same as ls or grep. You can't type ifgrep, so you can't type if[ either.
Because if[ is not if, you weren't in an if block, so then was unexpected, thus your syntax error.
Thus:
if [ "$a" -gt "$b" ] # Correct
not
if ["$a" -gt "$b" ] # Wrong because of lack of space
or
if[ $a -gt $b ] # Wrong because of lack of space and lack of quotes
(Leaving the quotes out leaves you open to a completely separate set of bugs).

"[:too many arguments" error in BASH

I'm learning BASH through HackerRank.There's an exercise in which the lengths of the triangle is given and then you need to find whether the triangle is isosceles,scalene or equilateral.I wrote the following code:
read a
read b
read c
if [ [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ] ]
then
echo "EQUILATERAL"
elif [ [ "$a" -eq "$b" ] || [ "$b" -eq "$c" ] ]
then
echo "ISOSCELES"
else
echo "SCALENE"
fi
But then I get the following error
solution.sh: line 4: [: too many arguments
solution.sh: line 7: [: too many arguments
solution.sh: line 7: [: too many arguments
Why is this happening? I tried long and hard to rectify it but nothing worked out
You can combine conditions either ommiting the surrounding brackets like this
if [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ]
or by combining the conditions with -a/-o like this
if [ "$a" -eq "$b" -a "$b" -eq "$c" ]
see http://wiki.bash-hackers.org/commands/classictest#and_and_or
&& and || are Bash list operators. In a chain of commands, the next command is executed only if the previous command returned 0 (&&) or nonzero (||).
[ is an alias for the Bash internal test command and has arguments such as -eq or -ne. ] ends its command line. Type help test for more information.
So if you write a conditional expression, you do not put the list operators inside brackets.
Try, for example, this instead of the respective line in your code:
if [ "$a" -eq "$b" ] && [ "$b" -eq "$c" ]
then
[ isn't a grouping operator in bash, you can't use it to group tests.
there are a number of different ways to express the tests you want to make, numeric evaluation mode is probably easiest to read
if (( a == b && b == c ))
if (( a == b || b == c || c == a ))
This is going to break if you have decimal fractions, but will work fine for integers.
[ is a conditional command, like an alias for sh's test built-in command.
[[ is the same for bash which has more test options.
So make a choice between [ and [[ but not [ [ which means two command.
Example:
# [ [ -n 'test' ] ]
bash: [: too many arguments
# [ -n 'test' ] && echo $?
0
# [[ -n 'test' ]] && echo $?
0

shell program does not show the value of the character given as input?

I am inputting a single character from the user and trying to print the ascii value of the character if it's value is >=97 and <=121
This is my code and it does not work.
echo "Enter a character"
read n
if ["'${n}" -ge 97 and "'${n}" -le 121]
then
print "%d","'$n"
fi
Error:
ascii.sh: 3: ascii.sh: ['a: not found
[ is a command in shell, aka test command.
You need spaces around [ and ].
Moreover, in order to compare integers you need to use < and >.
EDIT: In order to fix, you could say:
read n
asc=$(printf "%d" "'$n")
[[ "$asc" > 97 ]] && [[ "$asc" < 122 ]] && echo $asc
If you're using sh, you could change the last line to:
[ "$asc" -gt 97 ] && [ "$asc" -le 121 ] && echo $asc
Something like this will make it:
#!/bin/sh
min=97
max=121
echo "Enter a character"
read n
value=$(printf "%d" "'$n")
printf "The ASCII character of %s is %d.\n" "$n" "$value"
if [ "${value}" -le $min ] && [ "${value}" -le $max ]
then
printf "%d not in the range.\n" "$value"
else
printf "%d in the range.\n" "$value"
fi
Things that I changed:
- printf instead of print.
- ["'${n}" -ge 97 and "'${n}" -le 121] condition needed to be splited in two blocks:
if [ "${n}" -le 97 ] && [ "${n}" -le 121 ]

Bash Shell: What is the differences in syntax?

I've seen two ways in tutorials to do syntax for if statements in BASH shell:
This one wouldn't work unless I put quotes around the variable and added additional [ and ]:
if [[ "$step" -eq 0 ]]
This one worked without putting quotes around the variable and the additional [ and ] weren't needed:
if [ $step -ge 1 ] && [ $step -le 52 ]
Which is correct and best practice? What are the differences? Thanks!
"When referencing a variable, it is generally advisable to enclose its name in double quotes" -- http://tldp.org/LDP/abs/html/quotingvar.html
if [ $step -ge 1 ] && [ $step -le 52 ] can be replaced as
if [ "$step" -ge 1 -a "$step" -le 52 ]
if [[ "$step" -eq 0 ]] can be replaced as if [ "$step" -eq 0 ]
Also, suppose you have the following script:
#!/bin/bash
if [ $x -eq 0 ]
then
echo "hello"
fi
You get this error when you run the script -- example.sh: line 2: [: -eq: unary operator expected
But using if [ "$x" -eq 0 ]
You get a different error when you run the script -- example.sh: line 2: [: : integer expression expected
Thus, it is always best to put variables inside quotes...
if [[ .... ]] syntax is particularly useful when you have regex in the condition statement -- http://honglus.blogspot.com/2010/03/regular-expression-in-condition.html
EDIT: When we deal with strings --
#!/bin/bash
if [ $x = "name" ]
then
echo "hello"
fi
You get this error when you run the script -- example.sh: line 2: [: =: unary operator expected
But, if you use if [ "$x" = "name" ] it runs fine (i.e. no errors ) and if statement is evaluated as false, as value of x is null which does not match name.

Resources