How to prevent a script from being run more than once at any time

How to prevent a script from being run more than once at any time

This will prevent more than one instance of this script from running at any given time

#/bin/sh

LOCK_FILE=/var/run/${0##*/}.lock

if [ -e $LOCK_FILE ]; then
  OLD_PID=`cat $LOCK_FILE`
  if [ ` ps -p $OLD_PID > /dev/null 2>&1 ` ]; then
    exit 0
  fi
fi
echo $$ > $LOCK_FILE

# do your thing here

rm -f $LOCK_FILE
Advertisements

Shell Tricks part 2 – Why having the current working directory in your PATH is a bad idea

Why having the current working directory in your PATH is a bad idea

Heres’s an interesting consequence of having the current directory in your path:-

$ PATH=$PATH:.
$ echo echo something benign > 0a.sh
$ chmod 0700 0a.sh
$ *
something benign
$

Let’s see that again

$ set -xv
set -xv
+ set -xv
$ PATH=$PATH:$.
PATH=$PATH:.
+ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.
$ echo echo something benign > 0a.sh
echo echo something benign > 0a.sh
+ echo echo something benign
$ chmod 0700 0a.sh
chmod 0700 0a.sh
+ chmod 0700 0a.sh
$ *
*
+ 0a.sh bin boot dev etc home lib lost+found mnt opt proc root sbin tmp usr var
something benign
$

Notice how 0a.sh was executed as it was the first file in the list, and this could be any executable in the directory because the command sorts the commands in alphabetical order and arbitrarily expands the expression and faithfully executes it, whatever it is, and here lieth the danger, amongst others like replacing system commands unwittingly.

Beware, an accidental * could launch all kinds of mischief!

Shell Tricks Part 1 – Substituting basename, dirname and ls commands

Substituting basename, dirname and ls commands

In Bourne shell, it is possible to use the following variable expansions as substitutes for the basename, dirname and ls commands

$ MYVAR=/path/to/basename
$ echo ${MYVAR##*/}
basename
$ MYVAR=/path/to/dirname
$ echo ${MYVAR%/*}
/path/to
$ echo *
bin boot dev etc home lib lost+found mnt opt proc root sbin tmp usr var
$

Hows That?