help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Evaluations of backticks in if statements


From: Greg Wooledge
Subject: Re: [Help-bash] Evaluations of backticks in if statements
Date: Thu, 23 Feb 2017 08:56:07 -0500
User-agent: Mutt/1.4.2.3i

On Thu, Feb 23, 2017 at 01:01:30AM +0000, Ryan Marples wrote:
> I???ve seen bash statements like the following: if `cmd` ???

Probably just crappy code.  Most of the bash and sh code you will find
in this world is crap.

Also note that `...` is deprecated in favor of $(...) if you actually
do want a command substitution.

> This appears to run the body of the if when cmd exits successfully. But I
> don???t understand the mechanics of why. My understanding is that `cmd`
> (assuming in this case cmd prints nothing to either stdout nor stderr but
> exits successfully) should evaluate to an empty string, and then you???d be
> saying if ?????? ??? which should be false.

It would help if we knew what "cmd" really was, and what its output is.

In the simplest case, you have essentially this:

imadev:~$ if $(echo true); then echo yeah; else echo nope; fi 
yeah

The command inside $(...) is executed, and then its standard output is
"captured", and this becomes ANOTHER command, and THAT command is
executed, and the exit status of THAT command is what drives the "if".

In short, this code you've found is almost certainly wrong.

Compare:

imadev:~$ if $(echo false); then echo yeah; else echo nope; fi
nope

As you can see here, it's the exit status of the GENERATED command
(in this case, "false") that drives the "if".  The exit status of
the substituted command ("echo false") does not matter.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]