Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Command not found" when attempting integer equality in bash

Tags:

bash

Ok, this is probably going to be ultra obvious to anyone that has spent more time with bash than I have.

I'm trying to run this code:

#!/bin/bash

if ["1" -eq "2"] 
then
    echo "True"
else
    echo "False"
fi

but when I execute the file, it sends back

./test.sh: line 3: 1: command not found
False

There must be something major I'm missing. I've seen people use a semicolon after the brackets, this doesn't seem to make any difference... :S

like image 964
Margaret Avatar asked Dec 17 '10 08:12

Margaret


People also ask

How do I fix bash command not found?

Install a package Sometimes when you try to use a command and Bash displays the "Command not found" error, it might be because the program is not installed on your system. Correct this by installing a software package containing the command.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

How do you write not equal to in bash?

The not equal function in Ubuntu bash is denoted by the symbol “-ne,” which would be the initial character of “not equal.” Also included is the “! =” operator that is used to indicate the not equal condition. The exclamation point, i.e., “!


2 Answers

You need to add a space after the [ and before the ] like so:

if [ "1" -eq "2" ]

However, that way is deprecated and the better method to use is:

#!/bin/bash

if ((1 == 2)) 
then
    echo "True"
else
    echo "False"
fi
like image 194
SiegeX Avatar answered Sep 19 '22 17:09

SiegeX


yep eq is used only for arithmetic comparaisons.

for string comparison you have to use =

#!/bin/bash

if [ "1" = "2" ] 
then
    echo "True"
else
    echo "False"
fi

plus you need some space around the brackets.

like image 41
RageZ Avatar answered Sep 17 '22 17:09

RageZ