| +34 608 61 64 10



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


while true;

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"

                sleep 10;
    		echo "Nothing to do...\n"
	echo "Incorrect call needs one parameter"

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

How get the return command

Options to kill a process

Create a demon