Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I insisted on doing it in fewer than 4 lines and no sub-shell, then I think I'd use:</p> <pre><code>ACTION=${1:+' '} : ${ACTION:=echo} </code></pre> <p>This cheats slightly - it creates a blank action rather than an empty action if there is an argument to the script. If there is no argument, then ACTION is empty before the second line. On the second line, if action is empty, set it to 'echo'. In the expansion, since you (correctly) do not quote $ACTION, no argument will be passed for the blank.</p> <p>Tester (xx.sh):</p> <pre><code>ACTION=${1:+' '} : ${ACTION:=echo} echo $ACTION rm -f a b c </code></pre> <p>Tests:</p> <pre><code>$ sh xx.sh 1 rm -f a b c $ sh xx.sh echo rm -f a b c $ sh xx.sh '' echo rm -f a b c $ </code></pre> <p>If the last line is incorrect, then remove the colon from before the plus.</p> <hr> <p>If a sub-shell is acceptable, then one of these two single lines works:</p> <pre><code>ACTION=$([ -z "$1" ] &amp;&amp; echo echo) ACTION=$([ -z "${1+X}" ] &amp;&amp; echo echo) </code></pre> <p>The first corresponds to the first version shown above (empty first arguments are treated as absent); the second deals with empty arguments as present. You could write:</p> <pre><code>ACTION=$([ -z "${1:+X}" ] &amp;&amp; echo echo) </code></pre> <p>to make the relation with the second clearer - except you're only going to use one or the other, not both.</p> <hr> <p>Since the markdown notation in my comment confused the system (or I got it wrong but didn't get to fix it quickly enough), my last comment (slightly amended) should read:</p> <p>The notation <code>${var:+' '}</code> means 'if <code>$var</code> is set and is not empty, then use what follows the <code>+</code>' (which, in this case, is a single blank). The notation <code>${var+' '}</code> means 'if <code>$var</code> is set - regardless of whether it is empty or not - then use what follows the <code>+</code>'. These other expansions are similar:</p> <ul> <li><code>${var:=X}</code> - set <code>$var</code> to <code>X</code> unless it already has a non-empty value.</li> <li><code>${var:-X}</code> - expands to <code>$var</code> if it has a non-empty value and expands to <code>X</code> if <code>$var</code> is unset or is empty</li> </ul> <p>Dropping the colon removes the 'empty' part of the test.</p>
 

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