help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Syntax for if test


From: Eric Blake
Subject: Re: [Help-bash] Syntax for if test
Date: Mon, 05 Dec 2011 08:59:41 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:8.0) Gecko/20111115 Thunderbird/8.0

On 12/05/2011 08:21 AM, Bill Gradwohl wrote:
> I'm trying to work out the correct syntax to state a relatively simple if
> test.
> 
> What I want to say is :
> if a is true or (b is true and c is true) then do something.

standard-compliant:

if test a... || { test b.. && test c...; }; then <do something>

or bash-extension:

if [[ a... || ( b... && c.. ) ]]; then <do something>

> 
> I can't seem to get the syntax correct using a standard [ ] notation.
> 
> if [ $(some executable) -o ( $(some executable) -a $(some executable ) ];

test a... and [ a... ] are identical; I tend to use 'test' over '[', but
either will work.  [[ is nicer to use because it has simpler quoting
rules, but it is not (yet) part of POSIX, so you are likely to run into
portability problems to other shells.

> I've tried breaking the test up into multiple tests (as shown), as a single
> [ ] test using ( ) to group the -a , and numerous other arrangements, and
> none work. I either get bash syntax errors or the line of code simply
> doesn't do what I want.
> 
> if [ $(echo "${templateMachine}"|egrep -q '\.') -a $(grep -q
> "${templateMachine}" /etc/hosts|grep -q $(hostname -s)) ] || [
> "${templateMachine}" == $(hostname -s) ]; then

Missing quoting.  test -a and test -o are not portable.  egrep and grep
behave the same for the regex of a literal '.'.  grep -q is not
portable.  Piping grep -q output into another grep will never match.  If
you want your test based on exit status rather than on (non-)emptiness
of a string, then don't use [.  Rather than use grep for an exit status,
you can use shell builtins and shave a process.  test == is not portable.

Try:

if { [ -n "$TemplateMachine" ] && grep "$templateMachine" /etc/hosts |
grep -q "$(hostname -s)"; } || [ x"$templateMachine" = "x$(hostname -s)"
]; then

> Lastly, I've read up on [[ ]] numerous times in man bash and I can't quite
> wrap my head around it. Can someone point at an alternate explanation on
> the features and benefits of using [ ] vs [[ ]] ?

Standards-compliance vs. ease of use.  [[ lets you get away with less
quoting (since it is part of the shell grammar rather than an external
program, bash knows whether an argument was passed literally or as the
result of an expansion), and also has more power (=~ and such allow
regex matching).

-- 
Eric Blake   address@hidden    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]