Returning a boolean from a Bash function

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

提交回复
热议问题