exsnake
exsnake

Reputation: 1833

How to know if a process is user or root in bash, linux

I need to know if a process is from the user or not. I'm using this code:

#c is the PID
Aid=$(cat /proc/$c/status | grep -e ^Uid) 
Uid="Uid:   0   0   0   0"
if [ "$Aid" != "$Uid" ]; then
    echo "is from user"
fi

But I'm not very comfortable with the "tabs" in the string, i think that maybe can cause some unexpected behavior.

Is there any other way to do it?

Upvotes: 1

Views: 531

Answers (1)

that other guy
that other guy

Reputation: 123690

You can get the UID of a certain pid without parsing using ps -o uid= -p $pidhere:

mypid=1
if uid=$(ps -o uid= -p "$mypid")
then
  if [[ $uid -eq 0 ]]
  then
    echo "The process runs as root"
  else
    echo "The process runs as something else"
  fi
else
  echo "The process doesn't exist"
fi

Upvotes: 5

Related Questions