awk in shell scripts examples
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
testScriptfile:
vi testScript
- add the following lines to the
testScriptfile:
#!/bin/bash
sleep 5000
- make
testScriptfile executable:
chmod +x testScript
- execute
testScript:
./testScript
- in another terminal window, check if the script is being executed:
ps -ef | grep testScript
Outputs:
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}'
Outputs:
670
Explanation:
ps -efdisplays all currently active system processes in full-format,| grep testScriptnarrows output to the one containing only the lines with 'testScript' string,| grep -v grepfilters out the lines containing 'grep' string (in other words,grep testScriptcommand 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 theIFSvariable value.