So,
Being new to GIT and thus extremely rusty in my bash commands and scripting I've been looking around for different syntax and scripting help. Now, I've found a lot of help and have been able to create the scripts and alias that will make my Git experience more pleasant.
However, I came across some nuances that seem to confuse me, specifically related to the "if" command.
if [ -z $1 ] ; #<- Zero length string
if [[ -z $1 ]] ; #<- Also Zero Length String
if [[ "$1" == -* ]] ; #<- Starts with - (hyphen)
if [ -z $1 ] && [ -z $2 ] ; #<- both param 1 & 2 are zero length
if [[ -z $1 ]] && [[ -z $2 ]] ; #<- Also both param 1 & 2 are zero length
if [[ "$1" == -* ]] || [[ "$2" == -* ]] ; #<- Either param 1 or 2 starts with -
if [ "$1" == -* ] || [ "$2" == -* ] ; #<- Syntax Failure, "bash: ]: too many arguments"
Why the discrepancy? How to know when the [[ (double) is required and when a [ (single) will do?
Thanks
Jaeden "Sifo Dyas" al'Raec Ruiner
Best Answer
First off, note that neither type of bracket is part of the syntax for
if
. Instead:[
is another name for the shell built-intest
;[[ ... ]]
is a separate built-in, with different syntax and semantics.Here are excerpts from the bash documentation:
[
/test
[[ ... ]]
More simply said,
[
requires one to take the normal care needed for bash expressions, quote to avoid interpolation, etc. So a proper way of testing for$foo
being the empty string, or being unset, would be:or
It's important to quote in the first case, because setting
foo="a b"
and then testing[ -z $foo ]
would result intest -z
receiving two arguments, which is incorrect.The language for
[[ .. ]]
is different, and properly knows about variables, much in the way one would expect from a higher-level language than bash. For this reason, it is much less error-prone than classic[
/test
.