Skip to content

Instantly share code, notes, and snippets.

@beugley
Created October 1, 2015 13:35
Show Gist options
  • Save beugley/262d54204e1562e24e81 to your computer and use it in GitHub Desktop.
Save beugley/262d54204e1562e24e81 to your computer and use it in GitHub Desktop.
Shell: script that will start a process if it's not already running
#!/bin/ksh
###############################################################################
## Shell script that will start a process if it's not already running.
## Usage: start_if_not_running.ksh -n name
## where "name" is the name of the process. name must exist relative
## to the current directory, or contain a full path.
###############################################################################
function Print
{
print "`date +'%Y%m%d.%H%M%S'`: $*"
}
USAGE="Usage: `basename $0` -n name"
while getopts :n: args
do
case $args in
n) NAME=$OPTARG;;
:) Print "Invalid command line: $USAGE"
exit 1;;
\?) Print "Invalid command line: $USAGE"
exit 1;;
esac
done
if [[ "$NAME" == "" ]]
then
Print "$USAGE"
exit 1
fi
function GetPID
{
PID=`ps -ef | grep $NAME | grep -v grep | awk '{print $2}' | grep -v $$`
echo "$PID"
}
##
## Get the PIDs of all $NAME processes.
##
PID=$(GetPID)
PID_COUNT=`echo $PID | wc -w`
if ((PID_COUNT == 0))
then
Print "Starting $NAME"
if [[ ! -f $NAME ]]
then
Print "ERROR: Cound not find '$NAME'"
exit 2
else
nohup $NAME >$NAME.log 2>&1 &
PID=$(GetPID)
Print "PID is $PID"
fi
elif ((PID_COUNT == 1))
then
Print "$NAME already running as pid $PID"
else
Print "WARNING: Found $PID_COUNT instances of $NAME"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment