You are not logged in.

#1 2017-01-29 05:45:10

FlowIt
Member
Registered: 2014-10-25
Posts: 239

[Solved] Custom bash prompt

It's supposed to look like this:
username:$PWD followed by a single $
The username is either colored blue for all users except root, and magenta, if root. I want the final dollar sign to be green or red, depending on the exit code of the last command. I nearly got it working with the following line in my .bashrc. The problem is that the dollar sign at the end is always green. I assume this is because it actually takes the exit code of the echo command inside PS1. If I put the dollar sign at the beginning of the prompt it works fine.

PS1='$([ $EUID -eq 0 ] && echo "\e[0;35m" || echo "\e[0;34m")\u\e[0;0m:\W$([ $? -eq 0 ] && echo "\e[1;32m" || echo "\e[1;91m")$\e[0;0m '

Is there a way to ignore the exit codes from the subshell or how would I save $? in PROMPT_COMMAND in a temporary variable to use in PS1?

Last edited by FlowIt (2017-01-29 17:08:55)

Offline

#2 2017-01-29 16:16:39

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: [Solved] Custom bash prompt

Soon as you become root, bash reads /root/.bashrc (pwd) you better set the PS there, instead of 'complicated' lines that don't work.
I don't know if this work, but you could try and symlink your users bashrc to root and use a if statement to set PS, though, this may or may not be possible, haven't tried. wink

Edit:
Just for fun I tried the symlinking thing with a if statement, that works fine becoming root through 'sudo su' and nicely 'paint' the prompt.

Last edited by qinohe (2017-01-29 16:34:48)

Offline

#3 2017-01-29 17:08:42

FlowIt
Member
Registered: 2014-10-25
Posts: 239

Re: [Solved] Custom bash prompt

As much as I appreciate your help, it does not answer the question. Changing the color based on the user works fine. And yes, it could be easier to just set at least this part of the promt in /root/.bashrc. My point is: $? gets overwritten in PS1 because other commands are run before I actually use $?. In my case it's for coloring the user, but it needn't be. There are so many cool things one can do with PS1, so I am looking for a generic way to save $?.
Edit: Setting RET_TEMP=$? in PROMT_COMMAND and use RET_TEMP in PS1 does the trick, I just had a silly quoting mistake. Solved.

Offline

Board footer

Powered by FluxBB