6

I have a bash script that forwards down to a mixture of other shell scripts and python scripts. If any of those scripts fail or if the user cancels the script (CTRL+C) I want to perform some cleanup in all cases.

Many users can SSH into a linux box under the same OS user and initiate builds. This is our build server. The script needs to write a "build.lock" file or something, that will be cleaned up whenever the script exits in anyway (error, user exit, etc). If the script is run again before the first one was done executing, it should check for the "build.lock" file and refuse to proceed.

I'm assuming this is the best way to prevent parallel execution of the script. We're using Bash on Ubuntu. Below is the script itself:

#!/bin/bash -e
pushd build-server-scripts > /dev/null
./build.sh "$@"
popd > /dev/null

Is my idea a good solution to this problem? If so, what is the way to implement it? If not, what other ideas would everyone recommend? I'm inexperienced with Bash scripting so I learn as I go.

1
  • I don't have time for a full answer at the moment, but this file at 12.2.3.2 seems to do pretty much exactly what you're doing. Good luck! Commented Jun 10, 2014 at 23:15

2 Answers 2

8

If I understand your problem correctly you might want to look into bash's trap You can define a trap function that is called upon script exit

# Set up a cleanup function to be triggered upon script exit
__cleanup ()
{
    [[ -f "build.lock" ]] && rm "build.lock"
}

trap __cleanup EXIT
Sign up to request clarification or add additional context in comments.

Comments

4

When using trap don't forget to propagate the received signal to the calling process:

__cleanup()
{
    SIGNAL=$1

    [[ -f "build.lock" ]] && rm "build.lock"

    # when this function was called due to receiving a signal
    # disable the previously set trap and kill yourself with
    # the received signal
    if [ -n "$SIGNAL" ]
    then
        trap $SIGNAL
        kill -${SIGNAL} $$
    fi
}

trap will be called like this in this case:

trap '__cleanup 1' HUP
trap '__cleanup 2' INT
trap '__cleanup 3' QUIT
trap '__cleanup 13' PIPE
trap '__cleanup 15' TERM

A nice explanation of proper signal handling can be found here:

Proper handling of SIGINT/SIGQUIT

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.