John Barnes John Barnes - 1 year ago 53
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?

Cheers
John

Answer Source

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

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

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
0

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 $?
0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download