Bash conditional prompt?

Hi,

Does anyone know any way of making bash prompt extended with conditional content?

Example:

export PS1="[[ ${USER} = 'root' ]] && echo '#' || echo '\$'" # This won't work - prompt is not executed
# export PS1="\$" # This is an existing but also working equivalent

I would like to use more complex conditionals than in the given example.

My main system's /etc/profile contains the following:

case $UID in
0)
  export PS1="\[\e[31m\][root@leonov]\[\e[0m\] "
  export PS2="\[\e[31m\][...........]\[\e[0m\] "
;;
1000)
  export PS1="\[\e[32m\][house@leonov]\[\e[0m\] "
  export PS2="\[\e[32m\][............]\[\e[0m\] "
;;
esac

Just to be clear, no, you can't put it in the variable itself.

you can try :b:

[[ "$(id -un)" == "root" ]] && export PS1='#' || export PS1='\$'

I am afraid that the answers given are not correct. There is a major difference between
conditional content in the prompt
and
conditional logic in the script that sets that prompt

The answer given by Corona688 seems to be the only one related.

Regards

As I understood it, Corona688 was only confirming what dr.house, and later ygemici had said, just more directly.

Given that, presenting alternatives was perfectly correct.

Both Kshell and bash expand variables at the time PS1 is written to the tty, and thus using $() the shell can be coaxed into doing what you want:

PS1='$(if [[ $USER == root ]]; then  echo "$PWD#"; else echo "$PWD%"; fi)'

I agree with earlier posts that suggest setting the prompt either in your profile, or the system profile, as being the smart way of doing it, but wanted to point out that it can be done this way.

3 Likes

Well that's certainly interesting. I didn't know any substitution whatsoever happened in single quotes...

[edit] This is special substitution that only works for the prompt variables, not in general.

Thanks,
That is what I was looking for!

Like I wrote:

FYI:
I wanted to get this:

PS4="\\c\\r\
${foregroundYellow}\
\$([[ \"\${0}\" != 'bash' ]] && echo \"\${0}\")\
:\
\${LINENO}\
${defaultColors}\
 + "
PS1="${PS1} ^[]0;\${IGotSomethingHere} \$(x=\$?;[[ \"\$x\" != '0' ]] && echo \"ERROR \$x\")^G"

What results in printing line like:
script.sh:123 + command_executed
And modified terminal window every time an error is thrown. Before I achieved similar result with trap on ERR.