My problem can be simplified down to making the following script work (which takes one command line argument):
#!/bin/bash
if ["$1" == "0"]; then
echo "good"
else
echo "bad"
fi
This should print good when I run script 0, but I can't get it to. I've tried various combinations of quotes around the numbers, and I've tried =, ==, and -eq. So... bash, how does it work?
Use double parentheses for arithmetic comparisons, then you don't need to worry about quotes and spacings, for example:
General rule: use
(( ))
for arithmetics and[[ ]]
for text and patterns.As others have said, [ is old Bourne shell syntax and there are few reasons for using it any more.
Use a space between the bracket and the argument
The
[
is actually a command. Do als /bin/[
or anls /usr/bin/[
. You'll see it's actually an executable file.The
[...]
is from the old Bourne shell days. Theif
command executes the statement, and if the exit code of that statement is a zero, the statement is considered true and the if clause is executed. If the exit code is not zero, the else clause is executed (if present).Try these:
You can see that
date
is a valid command and returns an exit code of 0 (the value of$?
), butdate -Q
isn't valid, and returns an exit code of 1.Now let's try them in the
if
statement:Now try this:
Originally, the
[...]
was an alias for thetest
command. The following are equivalent:and
This is why it's very important to put spaces around the
[
and]
. Because these are actually commands. In BASH, there's built into the shell, but they are commands. That's also why all the test parameters (things like-f
,-z
, and-eq
) all are prefixed with dashes. They were originally parameters for thetest
command.