John Barnes John Barnes - 4 years ago 145
Bash Question

Scripting to see if specific process is running as root

I am currently trying to right a shell script which will allow me to check a process is running with the correct user (root)

I assume I would first have to use ps -efl & grep for the process and if it is running with root = 1 otherwise = 0?


Answer Source

You can use pgrep , usually available by default in most distros:

$ pgrep -a -u root -x geany;echo $?
2794 geany tuesday.txt
$ pgrep -a -u root -x gean;echo $?

Use -x option for exact match, otherwise the process name will be considered as a pattern:

$ pgrep -a -u root gean;echo $?
2794 geany tuesday.txt

Return code ($?) is 0 if process found, 1 if not found.

To keep only the return code and not the process name/info (in case that process is up and running as root) you can redirect pgrep output to /dev/null :

$ pgrep -a -u root geany 1>/dev/null;echo $?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download