paolo@bimodesign.com | +34 608 61 64 10

Unclassifiable

        

Unix - shell check process running

Some weeks ago my friends asked me to help her writing a shell code for the university exams. The issue was to create a shell that checks if a process is running.
The unique input parameter will be the name of the process and the our shell process will run indefinitely. Then if we detect that the input name process is running so we'll prompt to the user if he wants to kill it or not.
My solution was this shell code

#!/bin/bash

while true;
do

if [ -n "$1" ]; then
        #Sacar solo el primer resultado del grep 
        stringprocess=$(ps aux|grep $1 | head -1) 

	#Sacamos el PID
        pid=$(pidof $1)

	if [ -n "$pid" ]; then
    		echo "Eliminar $stringprocess  - [yes or no]\n"
    		read promptvar 

    		case "$promptvar" in
    		yY] | [yY][Ee][Ss] )        
      	 		kill -9 $pid >/dev/null 2>&1
                        echo "Proceso $pid eliminado correctamente"
       			;;
    		[nN] | [n|N][O|o] )        
                        echo "You digit No"
       			;;
    		*) 
       			echo "Invalid input"
       			;;
    		esac

                sleep 10;
	else
    		echo "Nothing to do...\n"
	fi
else 
	echo "Incorrect call shell...it needs one parameter"
fi
done

where I used these commands in pipe

ps aux|grep $1 | head -1

so the return will be only one line like this

paolo     6442  1.9  0.7 699584 46376 ?        Sl   17:57   0:00 filezilla

instead of

paolo     6442  2.7  0.7 699584 46376 ?        Sl   17:57   0:00 filezilla
paolo     6527  0.0  0.0  14592  2560 pts/1    S+   17:57   0:00 grep --color=auto filezilla

With this other shell instruction

pidof $1

I got the pid number and if the pid exists ( = the process is running) and then the user will type Y/y, I'll use this command to kill it

kill -9 $pid >/dev/null 2>&1

You'll find a cleary explanation about the input/stderr Unix reading this link or this Stackoverflow resource for more details.
Finally, those are some unix resources that I used to solve the problem, cause It's impossible to remember all the details.

Option of ps unix command
http://www.binarytides.com/linux-ps-command

How get the return command
http://unix.stackexchange.com/a/16027
http://www.linuxquestions.org/questions/linux-newbie-8/how-to-pass-command-line-parameter-to-shell-script-254396/

Options to kill a process
http://stackoverflow.com/a/7096003
http://stackoverflow.com/questions/6437602/shell-script-to-get-the-process-id-on-linux/7096003#7096003

Create a demon
https://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
https://liberatucodigo.wordpress.com/2012/05/19/crear-demonio-en-linux-servicios/
http://www.linuxnix.com/2010/03/how-to-create-daemon-in-linux.html
http://www.dreamsyssoft.com/unix-shell-scripting/ifelse-tutorial.php
http://www.thegeekstuff.com/2010/07/bash-case-statement/