Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call bash function with boolean parameter?

Tags:

bash

unix

I have a function called install_cont that is called twice from my bash script. However, inside that function there is a code block that I want to execute only if the boolean parameter is true. In Python I would do:

def install_cont(expres=False):
    if expres:
         # Do some code...

install_cont(True)
install_cont() # Can call with default False

How do I achieve this in bash? Reading online, I understand that all variables are string. However, what is the best way to achieve a boolean-like parameter?

like image 285
Gilbert Williams Avatar asked Sep 19 '25 14:09

Gilbert Williams


1 Answers

Shell scripting doesn't have booleans, but it does have a convention for representing success as an integer. Confusingly for programmers coming from other languages, this is that 0 is success, and anything else is failure.

This is the basis of the if construct which runs a command, and tests its result for success. You can't test a variable directly with if, but you can use the test built-in, which "succeeds" if a particular test passes.

test is also spelled [ which is why you'll often see code with if [ ... ] - those brackets aren't part of the if syntax, they're just a command with a funny name. (Bash also has a [[ built-in with some extra features, but [ is more standard, so worth learning.)

The test command can perform various tests - examining numbers, checking the file system, etc. For a command-line option, you could test against the string true or false with the = binary operator.

So what you end up with is something like this:

install_cont() {
    # Name the parameter for convenience
    local expres="$1";

    if [ "$expres" = "true" ];
    then
         # Do some code...
    fi;
}

install_cont true
install_cont # default will not pass the test

If you want fancier parameters, you can have actual defaults with the slightly awkward ${foo:-default} and ${foo:=default} parameter expansion syntaxes. For example:

install_cont() {
    # Default the mode to "boring"
    local mode="${1:-boring}";

    if [ "$mode" = "exciting" ];
    then
         # Do some code...
    elif [ "$mode" = "boring" ];
    then
         # Do some code...
    else
         echo "Unrecognised mode";
    fi;
}
like image 133
IMSoP Avatar answered Sep 21 '25 08:09

IMSoP