bug-bash
[Top][All Lists]
Advanced

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

Re: unhelpful effect of '!' prefix on commands in conditionals - a bug ?


From: Eric Blake
Subject: Re: unhelpful effect of '!' prefix on commands in conditionals - a bug ?
Date: Fri, 13 Jun 2014 14:56:17 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.5.0

On 06/13/2014 02:42 PM, Jason Vas Dias wrote:
> Having defined a function _F to return a non-zero return status :
>   $ function _F () { return 255; }
> I'd expect to be able to test this return status in an if clause - but
> this is what happens:
>   $ if ! _F ; then echo '_F returned: '$?; fi
>   _F returned: 0

This behavior is required by POSIX.  The exit status of ! is either 0 or
1, depending on whether the exit status of the command it wrapped was
non-zero or zero.

> This behavior seems to me to be an instant source of confusion and bugs -
> does anyone agree with me that this is a bug ?

The only confusion here is that you are unaware that ! affects $?. Since
the behavior is standardized by POSIX and consistent with all other
shells, there is nothing to change in bash.

> 
> Is this really mandated by the standards ?

Yes.  Quoting POSIX:

http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02

If the pipeline does not begin with the ! reserved word, the exit status
shall be the exit status of the last command specified in the pipeline.
Otherwise, the exit status shall be the logical NOT of the exit status
of the last command. That is, if the last command returns zero, the exit
status shall be 1; if the last command returns greater than zero, the
exit status shall be zero.

> 
> Is there some other variable I could test to retrieve $? if it has
> been mangled by a '!'
> in the conditional ?

Don't use ! in the conditional.  Take time to grab the status yourself.

  $ if _F ; then :; else echo '_F returned: '$?; fi

> 
> Is there any other conclusion than : "if you want to access the return
> status of a
> function in an if clause , don't use '!' in the conditional" ?

Not just functions, but ANY command.

-- 
Eric Blake   eblake redhat com    +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]