[CentOS] C5 BASH IF

Chris Adams linux at cmadams.net
Sat Feb 14 16:59:46 UTC 2015


Once upon a time, Les Mikesell <lesmikesell at gmail.com> said:
> On Fri, Feb 13, 2015 at 11:54 PM, Always Learning <centos at u64.u22.net> wrote:
> >> 16 if  [ $file = "law00css" ]
> 
> You still missed the part about quoting variables.  You quote plain
> strings to hold embedded spaces together (or single-quotes to avoid
> parsing metacharacters).  You use double quotes around  $variables so
> they don't disappear completely if the variable isn't set, causing a
> syntax error.  To understand it completely you need to know the order
> of operations as the shell makes multiple passes over the line,
> parsing, processing metacharacters, and expanding variables.   And I
> don't know where to find a concise description of that any more.

The thing to remember is that originally, the left square bracket [ was
an external command (an alias of the "test" command).  The shell
interpreter just ran commands and tested the output.  So, consider
everything past the "if" as a single command, and treat it accordingly
(so quoting arguments just like you would to "ls" or something).

So, in the above line, $file would be expanded by the shell as part of
command argument processing, and it is empty/not set, the command would
be run as:

    [ = law00css ]

That's invalid syntax.  If instead, you call it with $file in quotes:

    [ "" = law00css ]

That's valid syntax (and then tests as false).

-- 
Chris Adams <linux at cmadams.net>



More information about the CentOS mailing list