I was trying to write a Bash script that uses an if
statement.
if [$CHOICE -eq 1];
The script was giving me errors until I gave a space after [
and before ]
as shown below:
if [ $CHOICE -eq 1 ];
My question here is, why is the space around the square brackets so important in Bash?
[
is a command and$CHOICE
should be an argument, but by doing[$CHOICE
(without any space between[
and$CHOICE
) you are trying to run a command named[$CHOICE
. The syntax for command is:[
is atest
command. So it requires space.From another question:
Once you grasp that
[
is a command, a whole lot becomes clearer![
is another way to spell "test
".However while they do exactly the same,
test
turns out to have a more detailed help page. Check...for more information.
Furthermore note that I'm using, by intention,
help test
and notman test
. That's becausetest
and[
are shell builtin commands nowadays. Their feature set might differ from/bin/test
and/bin/[
from coreutils which are the commands described in theman
pages.