Returning a boolean from a Bash function

前端 未结 10 1002
余生分开走
余生分开走 2020-12-07 07:02

I want to write a bash function that check if a file has certain properties and returns true or false. Then I can use it in my scripts in the \"if\". But what should I retur

10条回答
  •  再見小時候
    2020-12-07 07:54

    I encountered a point (not explictly yet mentioned?) which I was stumbling over. That is, not how to return the boolean, but rather how to correctly evaluate it!

    I was trying to say if [ myfunc ]; then ..., but that's simply wrong. You must not use the brackets! if myfunc; then ... is the way to do it.

    As at @Bruno and others reiterated, true and false are commands, not values! That's very important to understanding booleans in shell scripts.

    In this post, I explained and demoed using boolean variables: https://stackoverflow.com/a/55174008/3220983 . I strongly suggest checking that out, because it's so closely related.

    Here, I'll provide some examples of returning and evaluating booleans from functions:

    This:

    test(){ false; }                                               
    if test; then echo "it is"; fi                                 
    

    Produces no echo output. (i.e. false returns false)

    test(){ true; }                                                
    if test; then echo "it is"; fi                                 
    

    Produces:

    it is                                                        
    

    (i.e. true returns true)

    And

    test(){ x=1; }                                                
    if test; then echo "it is"; fi                                 
    

    Produces:

    it is                                                                           
    

    Because 0 (i.e. true) was returned implicitly.

    Now, this is what was screwing me up...

    test(){ true; }                                                
    if [ test ]; then echo "it is"; fi                             
    

    Produces:

    it is                                                                           
    

    AND

    test(){ false; }                                                
    if [ test ]; then echo "it is"; fi                             
    

    ALSO produces:

    it is                                                                           
    

    Using the brackets here produced a false positive! (I infer the "outer" command result is 0.)

    The major take away from my post is: don't use brackets to evaluate a boolean function (or variable) like you would for a typical equality check e.g. if [ x -eq 1 ]; then... !

提交回复
热议问题