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?
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. Theifcommand 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
dateis a valid command and returns an exit code of 0 (the value of$?), butdate -Qisn’t valid, and returns an exit code of 1.Now let’s try them in the
ifstatement:Now try this:
Originally, the
[...]was an alias for thetestcommand. 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 thetestcommand.