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"?
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.
The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement.
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.
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.
[
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"
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