Bash script example on working with PID

Here is an example on how to get the process ID of an application in bash script

#!/bin/bash

PIDLINE=`ps -d | grep some-application`
PID=`echo $PIDLINE | cut -d" " -f1`

if [ -z "$PID" ]; then
 echo "ERROR: unable to find script PID"
fi

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

exit 0

The nice thing about it is cut -d” ” -f1. What it does is to break the line into columns (-d ” ” is delimiter) and sends back the first column to output.

# ps ax | grep console 
 2905 ?        Ssl    0:38 /usr/sbin/console-kit-daemon
31889 pts/0    S+     0:00 grep console

# echo `ps ax | grep console` | cut -d" " -f1
2905

# echo `ps ax | grep console` | cut -d" " -f1-3
2905 ? Ssl


You may also like