Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to compare arguments with if statement?

Tags:

bash

shell

macos

I'm trying to compare an argument in bash under OSX using the following code...

 #!/bin/bash

if ["$1" == "1"]
then
        echo $1
else
        echo "no"
fi

But I keep getting the following error

$bash script.sh 1

script.sh: line 3: [1: command not found
no

How do I stop it from trying to evaluate "1"?

like image 676
Awalias Avatar asked Apr 12 '12 14:04

Awalias


People also ask

How do I compare two variables in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

What is if [[ ]] in Linux?

The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement.

How do you pass two conditions in an if statement in Linux?

Bash If Elif Statement then : if the previous condition is true, then execute a specific command; elif : used in order to add an additional condition to your statement; else: if the previous conditions are false, execute another command; fi : closes the “if, elif, then” statement.

How do you check if two variables are equal in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command.


1 Answers

[ is a test command, so you need a space between [ and "$1", as well as a space between "1" and the closing ]

Edit

Just to clarify, the space is needed because [ is a different syntax of the test bash command, so the following is another way of writing the script:

#!/bin/bash

if test "$1" == "1"
then
        echo $1
else
        echo "no"
fi

Which can be further simplified to

#!/bin/bash
[ "$1" == "1" ] && echo "$1" || echo "no"
like image 129
Alex Avatar answered Oct 26 '22 17:10

Alex