Here is s snippet of code to check if a file exists so you don’t end up having your script run twice and edit the same file accidentally.

LOCK_FILE=/var/lock/`basename $0`
(set -C; : > $LOCK_FILE) 2> /dev/null
if [ $? != "0" ]; then
echo “Lock File exists – exiting”
exit 1

### Place your script content here ###

trap ‘rm $LOCK_FILE’ EXIT

2 Responses to “Bash File Check Statement”
  1. Alex Brandt says:

    The trap should be at the top of the script after LOCK_FILE has been established so that if an unexpected interrupt happens the lockfile will still be removed.

    Also, why not simply:

    LOCK_FILE=/var/lock/$(basename $0)
    (set -C; : > $LOCK_FILE) 2>/dev/null || exit 1

    trap ‘rm $LOCK_FILE’ EXIT

    # SCRIPT

    I’m curious what outputing the colon to the lock file does. You should be able to remove that without loss of functionality. Just verified the colon is a noop at that location.

  2. Norbert Varzariu says:

    What’s wrong with if [[ -f "$file" ]] ?

    There are a couple of bad practices in here, first, use lowercase variable names to avoid accidential overriding of environmental vars. Second, like Ales says, the trap doesn’t make much sense there. Usually, if a program has a lockfile, this is for a purpose. Be it either to avoid having multiple instances running or as a simple mechanism to check the status of a program (you may have read dead, but lockfile exists)
    So, in most cases, programs are doing stuff (like writing files to disk). Now, what you want to trap are unusual interrupts. Like SIGINT, ABRT, HUP KILL etc.

    This would be it:

    lock=/var/lock/$(basename $0)
    error_exit() { echo “${@:-”unknown error”}”; exit 1; }
    # add the trap here
    trap ‘rm “$lock”; exit 1′ INT HUP KILL TERM
    # now check for the lock file, exit if it exists
    [[ -f "$lock" ]] && error_exit “lock file exists” || touch “$lock”
    # do stuff
    # if we send any of the signals, the trap will remove the “$lock” and exit then. that’s what we want.
    # usually, I write a little clean_up function and use it in the trap.

    # unset trap
    trap – INT HUP KILL TERM
    # if we’ve come this far, we can safely remove the lock
    rm -f “$lock”
    exit 0

    Remember, if you’re writing for bash explicitely, use the proper syntax.

Leave a Reply