Using awk in scripts

Get process ID

Supposing we have launched a testScript file execution and we would like to get it’s process ID:

ps -ef | grep testScript | grep -v grep | awk '{print $2}'

In order to demonstrate how this command works:

  • create a testScript file:
vi testScript
  • add the following lines to the testScript file:

sleep 5000
  • make testScript file executable:
chmod +x testScript
  • execute testScript:
  • in another terminal window, check if the script is being executed:
ps -ef | grep testScript

ygrebnov   670     9  0 20:08 pts/0    00:00:00 /bin/bash ./testScript
ygrebnov   674   610  0 20:09 pts/3    00:00:00 grep --color=auto testScript
  • finally, execute the command, which outputs the process ID:
ps -ef | grep testScript | grep -v grep | awk '{print $2}'



  • ps -ef displays all currently active system processes in full-format,
  • | grep testScript narrows output to the one containing only the lines with ‘testScript’ string,
  • | grep -v grep filters out the lines containing ‘grep’ string (in other words, grep testScript command has its own process, which we want to remove from the output),
  • | awk '{print $2}' prints the second field of the input line. A ‘field’ in a line in awk is a group of characters separated by a character in the IFS variable value.