How do I tell if zsh is running with privileges?

2

In my .zshrc, I have commands that launch instances of various program, like Mozilla Firefox and Evolution. I obviously do not want to launch them as root so I want to check whether I am root before I launch them. How do I do this?

Demi

Posted 2013-12-15T03:05:18.663

Reputation: 718

Answers

2

You can use e.g. such a conditional statement:

PRGCMD="firefox"
PRGUSR="user"
if [[ $UID == 0 || $EUID == 0 ]]; then
   # root
   echo Running programm as User $PRGUSR
   sudo -u $PRGUSR ${(z)PRGCMD}
else
   ${(z)PRGCMD}
fi

It checks first, if the real user ID or the effective user id is zero, that is root.

If so, it uses sudo to run the program defined in the variable PRGCMD as the user definded in the variable PRGUSR. (You can omit this line if you want only the warning message.)

${(z)PRGCMD} splits words as if zsh command line in case PRGCMD contains spaces, i.e. parameters to the program.

A short variant, which only runs the program as non-root is: [[ $UID != 0 || $EUID != 0 ]] && firefox


Additionally you perhaps want to include %# into your prompt, so you can see that your current shell is privileged. From man zshmisc:

%#     A `#' if the shell is running with privileges, a `%' if not.  Equivalent to `%(!.#.%%)'.  The definition of `privileged', for  these
       purposes,  is that either the effective user ID is zero, or, if POSIX.1e capabilities are supported, that at least one capability is
       raised in either the Effective or Inheritable capability vectors.

The code judging if the shell is running with privileges (defined in privasserted() in utils.c) can IMHO not be done in shell code, so if you want the exact same behavior it's probably the best to parse the output of the %# prompt expansion:

[[ $(print -P "%#") == '#' ]] && echo shell privileged || echo shell not privileged

mpy

Posted 2013-12-15T03:05:18.663

Reputation: 20 866

1Or if you like squiggles: [[ ${(%):-%#} = \# ]] && echo root – Tom Hale – 2018-07-08T08:50:56.303

I thought of this. However, it is possible for the shell to be non-root and still have extra privileges - I would like to do the same check %# in the prompt does. – Demi – 2013-12-15T10:39:19.470

1@Demetri: I extended my answer to address the behavior of the %# prompt expansion. – mpy – 2013-12-15T10:58:12.173

@Demetri : I'm curious if the parsing of print -P "%#" solved your problem. If yo, please consider to accept my answer :). – mpy – 2013-12-21T10:36:44.343

1Ah yes, it did solve the problem! Sorry – Demi – 2013-12-21T10:38:49.647