Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>What should an if statement do when the condition is a command substitution where the command produces no output?</p> </blockquote> <p>Output doesn't matter. What matters is the <em>exit code</em>:</p> <pre class="lang-none prettyprint-override"><code> if list; then list; [ elif list; then list; ] ... [ else list; ] fi The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true. </code></pre> <p>If you replace your <code>$(echo true)</code> and <code>$(echo false)</code> with something else you will probably see what is going on:</p> <pre><code>$ if $(echo false) ; then echo yes ; else echo no ; fi no $ if $(echo command-does-not-exist) ; then echo yes ; else echo no ; fi command-does-not-exist: command not found no $ </code></pre> <p>The <code>$(..)</code> runs the command and then <code>if</code> <em>executes the results</em> (in this case, just <code>true</code> or <code>false</code> or <code>does-not-exist</code>). An empty <code>$()</code> starts a subshell which successfully runs to completion and returns an exit code of <code>0</code>:</p> <pre><code>$ if $() ; then echo yes ; else echo no ; fi yes </code></pre> <p>Aaron raised some interesting points:</p> <pre><code>$ if $(echo true; false) ; then echo yes ; else echo no ; fi yes $ if $(echo 'true ; false') ; then echo yes ; else echo no ; fi yes $ if true ; false ; then echo yes ; else echo no ; fi no $ if $(echo false ; true) ; then echo yes ; else echo no ; fi no $ if $(echo 'false ; true') ; then echo yes ; else echo no ; fi no $ if false ; true ; then echo yes ; else echo no ; fi yes $ </code></pre> <p>It appears that when executing a command constructed via the <code>$()</code> subshell, the first command's exit status is what matters.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload