Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a tar backup script that runs once a month. It runs at night through cron. I also have a power schedule that reboots the server at 4.15 every night.

The problem is that the server reboots while the tar script is running.

Can I add something to the beginning and end of a bash script to disable a reboot while the script is active?

share|improve this question
    
… run the script earlier? –  slhck May 29 '12 at 10:33

1 Answer 1

There is a discussion of how to implement a mutex lock in the Bash FAQs here:

http://mywiki.wooledge.org/BashFAQ/045

You could implement something similar, but make your reboot script loop until the lock is free. I haven't tested the following, but here's a starting point:

Tar script:

#!/bin/bash

lockdir=/tmp/myscript.lock

if mkdir "$lockdir"
then    # directory did not exist, but was created successfully
    echo >&2 "successfully acquired lock: $lockdir"
    trap 'rm -rf "$lockdir"' 0    # remove directory when script finishes
    # continue script
else
    echo >&2 "cannot acquire lock, giving up on $lockdir"
    exit 0
fi

# DO YOUR ORIGINAL TAR SCRIPT HERE

Reboot script:

#!/bin/bash

lockdir=/tmp/myscript.lock

while true; do
    if mkdir "$lockdir"
    then    # directory did not exist, but was created successfully
        trap 'rm -rf "$lockdir"' 0    # remove directory when script finishes
        break    # continue with script
    else
        sleep 5  # sleep for 5 seconds and try again
    fi
done

# RUN YOUR REBOOT COMMANDS HERE
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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