Skip to content

Instantly share code, notes, and snippets.

@jjrh
Created July 12, 2016 16:26
Show Gist options
  • Save jjrh/66fbe2c566e1fd3c0bddbec7db4e3218 to your computer and use it in GitHub Desktop.
Save jjrh/66fbe2c566e1fd3c0bddbec7db4e3218 to your computer and use it in GitHub Desktop.
checks if a program is running, if not, it tries to start it. # after 3 tries, if the program hasn't started we print out the error # and return.
#!/bin/sh
# checks if a program is running, if not, it tries to start it.
# after 3 tries, if the program hasn't started we print out the error
# and return.
errors=""
# uses pgrep to find the running process.
check_prog ()
{
if [ $count -eq 3 ]
then
printf "\t *** issue starting:'$1',\t '$errors' \n"
return
else
count=$(expr $count + 1)
fi
if [ $(pgrep -x "$1") ]
then
printf "\t * %-20s (running: %10s\n" "$1" "pid: $(pgrep -x "$1"))"
else
if [ $count -eq 1 ]
then
printf "\t * $1 not running, starting up\n"
fi
errors=$($1 2>&1)
check_prog $1
fi
}
# uses grep to find the running process.
# this allows one to give a fuzzy match for the running program
#
# in the case of beet bpd, it's grep shows up as
# 22695 pts/9 Sl 0:02 /usr/bin/python /usr/local/bin/beet bpd
# doing pgrep 'beet bpd' won't find the process due to the /usr/bin/python junk.
# this method also support command line arguemnts which check_prog does not.
check_prog_grep ()
{
if [ $count -eq 3 ]
then
printf "\t *** issue starting:'$1',\t '$errors' \n"
return
else
count=$(expr $count + 1)
fi
# if [ $(pgrep -x "$1") ]
running="$(ps ax | grep "$*" | grep -v "grep $*")"
if [ "$running" ]
then
PID=$(echo "$running" | cut -d " " -f1)
printf "\t * %-20s (running: %10s\n" "$*" "pid: $PID)"
else
if [ $count -eq 1 ]
then
printf "\t * $* not running, starting up\n"
fi
($* > /dev/null &)
check_prog_grep $*
fi
}
count=0
check_prog_grep beet bpd
count=0
check_prog mpdscribble
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment