Returning a boolean from a Bash function

前端 未结 10 965
余生分开走
余生分开走 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:40

    It might work if you rewrite this function myfun(){ ... return 0; else return 1; fi;} as this function myfun(){ ... return; else false; fi;}. That is if false is the last instruction in the function you get false result for whole function but return interrupts function with true result anyway. I believe it's true for my bash interpreter at least.

    0 讨论(0)
  • 2020-12-07 07:42

    Use the true or false commands immediately before your return, then return with no parameters. The return will automatically use the value of your last command.

    Providing arguments to return is inconsistent, type specific and prone to error if you are not using 1 or 0. And as previous comments have stated, using 1 or 0 here is not the right way to approach this function.

    #!/bin/bash
    
    function test_for_cat {
        if [ $1 = "cat" ];
        then
            true
            return
        else
            false
            return
        fi
    }
    
    for i in cat hat;
    do
        echo "${i}:"
        if test_for_cat "${i}";
        then
            echo "- True"
        else
            echo "- False"
        fi
    done
    

    Output:

    $ bash bash_return.sh
    
    cat:
    - True
    hat:
    - False
    
    0 讨论(0)
  • 2020-12-07 07:42

    I found the shortest form to test the function output is simply

    do_something() {
        [[ -e $1 ]] # e.g. test file exists
    }
    
    do_something "myfile.txt" || { echo "File doesn't exist!"; exit 1; }
    
    0 讨论(0)
  • 2020-12-07 07:47

    Following up on @Bruno Bronosky and @mrteatime, I offer the suggestion that you just write your boolean return "backwards". This is what I mean:

    foo()
    {
        if [ "$1" == "bar" ]; then
            true; return
        else
            false; return
        fi;
    }
    

    That eliminates the ugly two line requirement for every return statement.

    0 讨论(0)
  • 2020-12-07 07:48

    Use 0 for true and 1 for false.

    Sample:

    #!/bin/bash
    
    isdirectory() {
      if [ -d "$1" ]
      then
        # 0 = true
        return 0 
      else
        # 1 = false
        return 1
      fi
    }
    
    
    if isdirectory $1; then echo "is directory"; else echo "nopes"; fi
    

    Edit

    From @amichair's comment, these are also possible

    isdirectory() {
      if [ -d "$1" ]
      then
        true
      else
        false
      fi
    }
    
    
    isdirectory() {
      [ -d "$1" ]
    }
    
    0 讨论(0)
  • 2020-12-07 07:51
    myfun(){
        [ -d "$1" ]
    }
    if myfun "path"; then
        echo yes
    fi
    # or
    myfun "path" && echo yes
    
    0 讨论(0)
提交回复
热议问题