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

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



-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Fri, Aug 17, 2018 at 12:34:38PM +0100, Clive Standbridge wrote:

[...]

> > $ false
> > $ test $? && echo ok || echo error $?
> 
> The second $? in that line is different from the first; it's the exit
> status of "test". That can be demonstrated, with a corrected test
> command, by

No, because when the $? is expanded, the test hasn't run yet. This $?
*is* the (stringified) exit status of false, as can be seen in this
sequence:

  tomas@trotzki:~$ false
  tomas@trotzki:~$ test $? -eq 1 && echo "False"
  False
  tomas@trotzki:~$ true
  tomas@trotzki:~$ test $? -eq 1 && echo "False"
  tomas@trotzki:~$ 

> $ grep stuff /no/such/file
> grep: /no/such/file: No such file or directory
> $ echo $?
> 2

(as, BTW., *this* $? is not (yet) echo's exit status)

> $ grep stuff /no/such/file
> grep: /no/such/file: No such file or directory
> $ test $? -eq 0 && echo ok || echo error $?
> error 1

This one (eval goes left-to-right) should be the "test $? -eq 0"'s exit
status (it's not 0, so the && branch isn't taken).

> As was mentioned in an earlier reply, you can get round that by saving
> the exit status in a variable, e.g.

If you find yourself stashing too much in variables, you're holding
it wrong (sometimes you must, though).

> $ grep stuff /no/such/file
> grep: /no/such/file: No such file or directory
> $ RET=$?
> $ test $RET -eq 0 && echo ok || echo error $RET
> error 2

This is better spelt as

  grep stuff /no/such/file && echo ok || echo error $?

(or, se Greg's post downthread):

  if grep stuff /no/such/file ; then
    echo ok
  else
    echo error $?
  fi

Unless you need that exit status later in your script. Then,
stashing it in a variable may make sense.

Cheers
- -- tomás
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAlt2zzMACgkQBcgs9XrR2kY2JACfeuDdw9kGedXQtlErfgzIspBp
3MYAn15g56XpCCfmr7yOgu5OJfcvPjM0
=IPFY
-----END PGP SIGNATURE-----


Reply to: