Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

in zsh you can have a %# in your PS1 (or whatever PROMPT variable) which basically means display % if user or display # if root. I'm wondering if there is any way to affect this so that the % or # changes colors depending on whether it's a user or root (a red for root, a blue for user ) the obvious way is just to change the PS1 in my root's ~/.zshrc but considering this is already a special symbol I'm wondering if there isn't perhaps a way I can use the same PS1 for both... something specific to %# like it is for zsh ( I'm sure there are other hacks I could do too like an if then statement ).

share|improve this question

2 Answers 2

up vote 3 down vote accepted

%(!.%{\e[1;31m%}%m%{\e[0m%}.%{\e[0;33m%}%m%{\e[0m%})

That should work to change the hostname (%m) a different color (red) if you are root. I don't have a zsh shell to test it on but it looks correct.

Here's why:

%(x.true.false) :: Based on the evaluation of first term of the ternary, execute the correct statement. '!' is true if the shell is privileged. In fact %# is a shortcut for %(!.#.%).

%{\e[1;31m%} %m %{\e[0m%} :: the %{\e[X;Ym%} is the color escape sequence with X as formatting (bold, underline, etc) and Y as the color code. Note you need to open and close the sequence around the term you are looking to change the color otherwise everything after that point will be whatever color. I've added spaces here around the prompt term %m for clarity.

http://www.nparikh.org/unix/prompt.php has more options and details around the color tables and other available options for zsh.

share|improve this answer
autoload colors
colors
PS1="%~ %{%(#~$fg[red]~$fg[blue])%}%#%{$fg[default]%} "

%(# tests whether the shell is running as root. Changing this to %(! tests whether the shell is running with elevated privileges (which covers things like newgrp, but not logging in as root).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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