Writing a build script with if statements and function calls

Yes, as you point out, since your function is always returning a 0 it will always return success. No matter what happens. The simplest solution is to not have your function return anything at all:

function clone {
    git clone /volume1/repos/project.git
    cd project
}

function build {
    docker build -t project .
}

Then, it will return the exit status of the last command run (from man bash):

when executed, the exit status of a function is the exit status of the last command executed in the body.

Of course, since the last command of your clone function is cd, that means that if the git clone fails but cd project succeeds, your function will still return success. To avoid this, you can save the exit status of the git command in a variable and then have your function return that variable:

function clone {
    git clone /volume1/repos/project.git
    out=$?
    cd project
    return $out
}

Or, perhaps better:

function clone {
    git clone /volume1/repos/project.git && cd project
}

By combining the commands, if either fails, your function will return failure.


Modify your functions to something like:

function clone {
    if git clone /volume1/repos/project.git; then
            cd project
            return 0
    else
            return 1
    fi
}

function build {
    docker build -t project .
}

This way if the commands within them fails the function will exit properly. Note you don't need to explicitly return anything for the build function as it will just return with the exit status of the docker command, however if you add more commands to it you may need to set it up similar to the clone function.

Tags:

Bash