[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Evaluations of backticks in if statements
From: |
Andy Chu |
Subject: |
Re: [Help-bash] Evaluations of backticks in if statements |
Date: |
Wed, 8 Mar 2017 01:32:42 -0800 |
On Tue, Mar 7, 2017 at 4:49 PM, Ryan Marples <address@hidden> wrote:
> Sorry for the long delay, was pulled off onto other things. Andy – I’m not
> 100% clear what your conclusion was. Taking Seth’s example earlier in the
> thread:
>
>
>
>> $ if `true`; then echo foo; fi
>
>> foo
>
>> $ if `false`; then echo foo; fi
>
>> $
>
>
>
> Can you walk me through the explanation of the result of these two command
> variations please?
Basically `true` and `false` evaluate to an argv of [] (length 0), in
contrast to argv of [""] (length 1).
It's impossible exec a command of zero arguments, so it just skips it
and uses the last value of $?, which happens to be the one from inside
the subshell. I'm not sure if this is really a special case or not --
it seems to fall out of the fact that $? is a variable mutated at
every command step in the interpreter loop.
But Chet Ramey pointed out the explicit rule in POSIX:
"If there is no command name, but the command contained a command
substitution, the command shall complete with the exit status of the last
command substitution performed."
If you are confused why `true` and `false` evaluate to [] and not
[""], define a function like this:
argv() { python -c 'import sys; print sys.argv[1:]' "$@"; }
And then note all these differences. Empty words are elided from the
argv array unless quoted.
$ argv a $empty b
['a', 'b']
$ argv a `true` b
['a', 'b']
$ argv a $(true) b
['a', 'b']
$ argv a "$empty" b
['a', '', 'b']
$ argv a "`true`" b
['a', '', 'b']
$ argv a "$(true)" b
['a', '', 'b']
Andy