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?


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

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

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
  • 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 Dec 15 '13 at 10:39
  • 1
    @Demetri: I extended my answer to address the behavior of the %# prompt expansion. – mpy Dec 15 '13 at 10:58
  • @Demetri : I'm curious if the parsing of print -P "%#" solved your problem. If yo, please consider to accept my answer :). – mpy Dec 21 '13 at 10:36
  • 1
    Ah yes, it did solve the problem! Sorry – Demi Dec 21 '13 at 10:38
  • 1
    Or if you like squiggles: [[ ${(%):-%#} = \# ]] && echo root – Tom Hale Jul 8 '18 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.