[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: |
Thu, 23 Feb 2017 09:30:03 -0800 |
Hm I guess it's not so special. I will have to think about this a bit:
$ '' && echo YES
: command not found
$ `true` && echo YES
YES
$ `false` && echo YES
<no output, doesn't try to execute empty command>
-------------
$ ''; echo $?
: command not found
127
$ `true`; echo $?
0
$ `false`; echo $?
1
On Thu, Feb 23, 2017 at 9:26 AM, Andy Chu <address@hidden> wrote:
>
>
> On Thu, Feb 23, 2017 at 9:10 AM, Seth David Schoen <address@hidden>
> wrote:
>
>> Andy Chu writes:
>>
>> > Shell doesn't work this way. The syntax is "if command", and
>> >
>> > if `command`
>> >
>> > is a particular case of that which is not special in any way (and as you
>> > mention it's also not useful). There's no such thing as
>> >
>> > if ""
>> >
>> > where "" is a string/variable value -- the "" is interpreted a command
>> name.
>>
>> I agree with this interpretation, but I see behavior that I don't know
>> how to account for. Presumably the shell should be running the output
>> of the substituted command and then checking the return code of _that_,
>> which accounts for
>>
>> $ if `echo true`; then echo foo; fi
>> foo
>> $ if `echo false`; then echo foo; fi
>> $
>>
>> And it also accounts for
>>
>> $ if `echo wow`; then echo foo; fi
>> wow: command not found
>>
>> But since neither true(1) nor false(1) outputs anything, there shouldn't
>> be a difference between
>>
>> $ if `true`; then echo foo; fi
>> foo
>> $ if `false`; then echo foo; fi
>> $
>>
>> and indeed both of them should presumably complain about the unknown
>> command with an empty name -- but neither does, and they exhibit
>> different behavior from one another. So is there a special case after
>> all? I can't find a justification for this in the man page's
>> documentation of "if" or command substitution.
>>
>
>
> Yes, this is surprising to me:
>
> $ if ''; then echo TRUE; else echo FALSE; fi
> : command not found
> FALSE
>
> $ if `true`; then echo TRUE; else echo FALSE; fi
> TRUE
>
> $ if `false`; then echo TRUE; else echo FALSE; fi
> FALSE
>
> So basically the exit code of the subshell command IS checked, and it's
> not just treated as a word. There is some special interaction between if
> and subshell.
>
> Moreover I tested bash, dash, zsh, and mksh, and they all exhibit this
> behavior! But I don't see it in POSIX.
>
> http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
>
> Digging through the source should probably reveal this as a special case.
>
> I have a test framework running against all shells and mine is the only
> one that's "wrong" here!
>
> Andy
>
>
>
>
>