What command means “do nothing” in a conditional in Bash?

后端 未结 3 1686
孤独总比滥情好
孤独总比滥情好 2021-01-29 18:30

Sometimes when making conditionals, I need the code to do nothing, e.g., here, I want Bash to do nothing when $a is greater than \"10\", print \"1\" if $a

相关标签:
3条回答
  • 2021-01-29 19:09

    The no-op command in shell is : (colon).

    if [ "$a" -ge 10 ]
    then
        :
    elif [ "$a" -le 5 ]
    then
        echo "1"
    else
        echo "2"
    fi
    

    From the bash manual:

    : (a colon)
    Do nothing beyond expanding arguments and performing redirections. The return status is zero.

    0 讨论(0)
  • 2021-01-29 19:18

    You can probably just use the true command:

    if [ "$a" -ge 10 ]; then
        true
    elif [ "$a" -le 5 ]; then
        echo "1"
    else
        echo "2"
    fi
    

    An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:

    if [ "$a" -le 5 ]; then
        echo "1"
    elif [ "$a" -lt 10 ]; then
        echo "2"
    fi
    
    0 讨论(0)
  • 2021-01-29 19:18

    Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.

    I try to give a general rule by using the OPs example

    do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"

    we have to avoid a branch where $a gets more than 10, so $a < 10 as a general condition can be applied to every other, following condition.

    In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.

    So the OPs example with the rule applied may be restructured as:

    if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
    then
        echo "1"
    elif [ "$a" -lt 10 ]
    then
        echo "2"
    fi
    

    Just a variation of the above, enclosing everything in the $a < 10 condition:

    if [ "$a" -lt 10 ]
    then
        if [ "$a" -le 5 ]
        then
            echo "1"
        else
            echo "2"
        fi
    fi
    

    (For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)

    0 讨论(0)
提交回复
热议问题