Help understanding the below two lines of code.

Posted on 2011-09-13
Last Modified: 2012-05-12
Can anyone explain me what is the logic/meaning for the below code. I am new to shell scripting.

if [ -n "$(ps -ef|egrep system_cron |egrep bash|egrep -v ${PID})" ]
     ps -ef|awk '/system_cron/&&/bash/&&/'"${PID}"'/{print $2,$3}'|xargs kill
     exit 0
Question by:new_perl_user
  • 2
LVL 23

Accepted Solution

Maciej S earned 500 total points
ID: 36531351
if [ -n "$(ps -ef|egrep system_cron |egrep bash|egrep -v ${PID})" ]

-n means if following string is not empty. In your case the string is output from command:
ps -ef | egrep system_cron | egrep bash | egrep v- ${PID}
So - if there is some output, then this condition is true.

If it is true, run:
ps -ef | awk '/system_cron/&&/bash/&&/'"${PID}"'/{print $2,$3}'|xargs kill
which means: print list of processes (ps -ef) and print only lines containing patterns "system_cron", "bash", and something which is stored in PID variable. Print only second and third fields from this line (or lines). Then, run kill with this fields as parameters (which will be process id and parent process id - as these are second and third fields in ps -ef output).
After running this kill command, stop executing your script (exit 0).

Author Comment

ID: 36531430

Thank you for the explanation and a small doubt too..

So are they trying to kill the previous process  or only the current one. because this code is written within
the same system_cron script.

Expert Comment

ID: 36531573
It depends where ${PID} is obtained from.

Author Comment

ID: 36532072
Thank you.

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This Windows batch file is useful for organizing image files from a digital camera or other source, but can have many other uses.  It simply renames the file(s) to match their create date.  For example, if you took a picture today at 1:40pm and the …
Utilizing an array to gracefully append to a list of EmailAddresses
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question