6

My build/deploy script does not behave as I was expecting. If clone or build fails it will still go on and call restart. I suspect its because I return 0, but how should I write if I want to return the result from the inner commands, and in "clone" I want to move into the cloned folder only if clone was successful. How would you improve this script?

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

function build {
    docker build -t project .
    return 0
}

function cleanup {
    ...
}

function restart {
    ...
    docker run ...
}

trap cleanup EXIT

if clone && build; then
    restart
    exit 0
else
    echo Failed...
    exit 1
fi
1
  • Your clone and build functions will always return 0 (they cannot fail)
    – jesse_b
    Feb 12, 2020 at 18:35

2 Answers 2

13

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.

0
4

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.