You need to understand what [
means. Originally, this was a synonym for the /bin/test
command. These are identical:
if test -z "$foo"
then
echo "String '$foo' is null."
fi
if [ -z "$foo" ]
then
echo "String '$foo' is null."
fi
Now, you can see why spaces are needed for all of the parameters. These are parameters and not merely boolean expressions. In fact, the test manpage is a great place to learn about the various tests. (Note: The test
and [
are built in commands to the BASH shell.)
if [ $os_type=="Darwin" ]
then
This should be three parameters:
If you use single square brackets, you should be in the habit to surround your parameters with quotation marks. Otherwise, you will run into trouble:
foo="The value of FOO"
bar="The value of BAR"
if [ $foo != $bar ] #This won't work
then
...
In the above, the shell will interpolate $foo
and $bar
with their values before evaluating the expressions. You'll get:
if [ The value of FOO != The value of BAR ]
The [
will look at this and realize that neither The
or value
are correct parameters, and will complain. Using quotes will prevent this:
if [ "$foo" != "$bar" ] #This will work
then
This becomes:
if [ "The value of FOO" != "The value of BAR" ]
This is why it's highly recommended that you use double square brackets for your tests: [[ ... ]]
. The test looks at the parameters before the shell interpolates them:
if [[ $foo = $bar ]] #This will work even without quotation marks
Also, the [[ ... ]]
allows for pattern matching:
if [[ $os_type = D* ]] # Single equals is supported
then
path="/usr/local/share/"
elif [[ $os_type == L* ]] # Double equals is also supported
then
path="/home/share/"
else
echo "${os_type} is not supported"
exit 1
fi
This way, if the string is Darwin32
or Darwin64
, the if
statement still functions. Again, notice that there has to be white spaces around everything because these are parameters to a command (actually, not anymore, but that's the way the shell parses them).