Note that there are some explanatory texts on larger screens.

plurals
  1. POBash parameter expansion
    primarykey
    data
    text
    <p>I have a script which uses the following logic:</p> <pre><code>if [ ! -z "$1" ]; then # if any parameter is supplied ACTION= # clear $ACTION else ACTION=echo # otherwise, set it to 'echo' fi </code></pre> <p>This works fine, as-is. However, in reading the <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="nofollow">Shell Parameter Expansion</a> section of the <code>bash</code> manual, it seems this should be able to be done in a single step. However, I can't quite wrap my head around how to do it.</p> <p>I've tried:</p> <pre><code>ACTION=${1:-echo} # ends up with $1 in $ACTION ACTION=${1:+} ACTION=${ACTION:-echo} # ends up always 'echo' </code></pre> <p>and a few ways of nesting them, but nesting seems to be disallowed as far as I can tell.</p> <p>I realize I've already got a working solution, but now I'm genuinely curious if this is possible. It's something that would be straightforward with a ternary operator, but I don't think bash has one.</p> <p>If this is possible, I'd like to see the logic to do this seeming two-step process, with no if/else constructs, but <strong>using only any combination of the <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="nofollow">Shell Parameter Expansion</a> features</strong>.</p> <p>Thank you.</p> <hr> <p><strong>EDIT</strong> for elderarthis:</p> <p>The remainder of the script is just:</p> <pre><code>find . -name "*\?[NMSD]=[AD]" -exec ${ACTION} rm -f "{}" + </code></pre> <p>I just want <code>ACTION=echo</code> as a sanity check against myself, hence, passing any argument will actually do the deletion (by nullifying ${ACTION}, whereas passing no args leaves echo in there.</p> <p>And I know TIMTOWTDI; I'm looking to see if it can be done with just the stuff in the Shell Parameter Expansion section :-)</p> <hr> <p><strong>EDIT</strong> for Mikel:</p> <pre><code>$ cat honk.sh #!/bin/bash ACTION=${1-echo} echo $ACTION $ ./honk.sh echo $ ./honk.sh foo foo </code></pre> <p>The last needs to have <code>ACTION=''</code>, and thus return a blank line/null value.</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.
 

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