[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Syntax for if test
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] Syntax for if test |
Date: |
Mon, 5 Dec 2011 14:50:17 -0500 |
User-agent: |
Mutt/1.4.2.3i |
On Mon, Dec 05, 2011 at 01:36:43PM -0600, Bill Gradwohl wrote:
> On Mon, Dec 5, 2011 at 9:51 AM, Greg Wooledge <address@hidden> wrote:
> > If you require grouping, then:
> >
> > if [ a ] || { [ b ] && [ c ]; }; then
> > something
> > fi
> Wait a minute. Where did curlys come from? I thought the manual said
> regular ( ) is needed.
> A semicolon is needed? I'll have to study that.
There are several different things going on here. Let's backtrack a
little bit.
First, there is something called "command grouping", which means putting
a bunch of commands together in one group. This is done with curly braces,
like so:
{
command one
command two
}
If we want to write it all on one line, then it looks like this:
{ command one; command two; }
Next, there is the || operator (conditional execution). This is something
that goes in between two commands, like so:
cd /path || exit 1
If we wanted to run *multiple* commands after the ||, then we could use a
command group to do it:
cd /path || { echo "I can't cd /path, so I'm going to kill myself"; exit 1; }
Third, we have the "if" syntax, which looks like this:
if COMMANDS
then
COMMANDS
fi
If we want to write a complex if command, it might look something like
this:
if cmd a || { cmd b && cmd c; }
then
foo bar
fi
In this example, we're running "cmd a" no matter what. If that succeeds,
then we'll skip the group containing "cmd b" and "cmd c", and run "foo bar".
If "cmd a" failed, then we'll try the group -- we'll run "cmd b", and if
that succeeds, then we'll run "cmd c", and if THAT succeeds, then we run
"foo bar". But if "cmd b" fails, we stop. And if "cmd c" fails, we also
stop.
You're getting confused because you're reading the documentation for the
"[[" command and thinking that it applies to "if". The "[[" command lets
you use parenthesized *expressions* (not commands):
if [[ ($a = "$b") || ($c = "$d" && -z $e) ]]; then ...
This has nothing to do with command groups.