Bash Script: Start irssi (or any process) if not already running via a cronjob

doug
Tue, 16 Mar 2010 19:16:50 +0000

I know there are a thousand of these available online. This is one I just wrote and wanted to make it a thousand and one. This script will start irssi if there is no irssi process available.

Save the following script somewhere (example /home/kay/bin/irssi_init.sh) and add the following to your crontab:

*/1 * * * * /home/kay/bin/irssi_init.sh >> ~/irssi_init.log

Replace ~/irssi_init.log with any file you'd like the output to be saved to or /dev/null if you don't care.

The script:

#!/bin/sh
procname=/usr/bin/irssi
sessionname='irc'
runcmd="screen -U -dmS $sessionname $procname"

username=`id -un`
existing_pids=`pidof -s $procname` # Get the first irssi PID available

echo [`date +%X`] RUNNING PIDS: "$existing_pids";

if [ -z $existing_pids ]; then
        startproc=true;
else
        # Found at least one instance
        my_pid=`ps -U $username -u $username -o pid= | grep "$existing_pids"`; # Filter to check the PID is mine

        echo [`date +%X`] MY RUNNING PIDS: "$my_pid";
        if [ -z $my_pid ]; then
                startproc=true;
        fi
fi

if [ ! -z $startproc ]; then
        echo [`date +%X`] Running "$runcmd";
        $runcmd;
else
        echo [`date +%X`] No need to start "$procname";
fi