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

Re: Bash true/false builtings undocumented? "false" not working?

Hash: SHA1

On Fri, Aug 17, 2018 at 07:29:47PM +1000, Zenaan Harkness wrote:
> On Fri, Aug 17, 2018 at 10:51:03AM +0200, Nicolas George wrote:
> > Zenaan Harkness (2018-08-17):
> > > But whilst the subsequent list of Bash builtin commands DOES include
> > > entries for ":" (the very first entry) and "test", it appears to fail
> > > to include entries for "true" and for "false".
> > 
> > Maybe because it does the same thing as the standard and non-builtin
> > true and false?
> > 
> > > $ test $? &&
> > 
> > Stop right there. "test $?" does not do what you think it does.
> Aha. It's actually the Special Parameter "?", aka "$?" that I did not
> understand - I was treating it as a value, when actually it is
> something that expands, i.e. into a string, and not something that is
> treated as true or false.

Everything expands in a shell. There are no "values". Or something :)

- -- tomás

> So!  I guess the way to test the EXPANSION of the the most recent
> exit status, is to test it as a string value, assuming use of the
> token "$?".
> Seems clunky.
> Is there a "cleaner" way to test the true/ error exit status other
> than using "$?", with bonus points for working in posix sh as well as
> Bash, ?

Hm. For example:

  true && echo "yep" || echo "nope"

(I know, I know ;-)

But typically, you'd check exit status right "on the spot" (for 'true'
it does look a bit grotty, yes :).

But sometimes you want to keep your exit status for later in the script.

There's more than one way to do it. You can, as you hinted at above,
just squirrel away "$?" and later check it against 0 or not. One
advantage of this is that some programs communicate a bit more through
the exit value (cf curl's man page under "EXIT CODES" for an extreme
example :)

There's another possibility which meshes pretty well with How Shells
Work (TM): squirrel away "true" or "false" in your condition variable:

  test_weather_station && SUNNY=true || SUNNY=false
  # more stuff
  # still more stuff
  # ...
  $SUNNY && echo yeah || echo booh

This works because depending on SUNNY's value, this last line (first)
expands to 'true && echo yeah || echo booh' (or 'false &&...').

Nifty. But if SUNNY's value is 'mumble', you might get an error message
"mumble: command not found" on stderr (and then a "booh" on stdout).

Whereas if SUNNY's value is "rm -Rf /" -- well, this one might have an
exit status of "success", so if the rm succeeds, it will say "yeah".

Caveat Scriptor.

- -- tomás
Version: GnuPG v1.4.12 (GNU/Linux)


Reply to: