Reputation: 402
I'm trying to customize my bash prompt. I want it so change color if I enter a command that doesn't exist, or for some other reason fails. I'm fairly new with coding bash scripts, so I looked at some other scripts so get some help, but something's not working. Here's my code:
export PROMPT_COMMAND="
PS1='`
if [ $? -eq 0 ];
then echo '
\[\033[00;32m\]┌─\[\033[00;35m\]\u\[\033[01;32m\]@
\[\033[00;35m\]\h\n\[\033[00;32m\]└─\[\033[01;32m\]
(\[\033[01;35m\]\W\[\033[01;32m\])\[\033[00;32m\]\$';
else echo '
\[\033[00;31m\]┌─\[\033[00;35m\]\u\[\033[01;31m\]@
\[\033[00;35m\]\h\n\[\033[00;31m\]└─\[\033[01;31m\]
(\[\033[35m\]\W\[\033[31m\])\[\033[00;31m\]\$';
fi`\[\033[0m\]'"
I do not have any linebreaks in the actual code, since that would be messy with PS1, I just added them to make the code easier to read.
So, I want to compare the exit status, $?, to 0. For some reason the variable $? doesn't change at all in the script. It just remains 0, so the first condition is always true, even when I issue a faulty command. I've tried adding echo $? to the code before the if-case, and this always returns 0, even if issuing echo $? as a command to the terminal returns something different. I've tried copying working code into mine, but that doesn't solve it either. Also, it worked when I used ' as the outer citation and " as the second. I changed this because the script wouldn't accept ( as a character otherwise.
Any ideas why this is and how I can fix it?
Upvotes: 3
Views: 640
Reputation: 11012
Just as as a follow up to H.-Dirk Schmitt's great answer, this works for me (I'm not going to bother explaining the code, that has been done already better than I could);
PS1='`
if [ $? -eq 0 ];
then echo -n "\[\033\[00;35m\]\u\[\033\[01;32m\]@\[\033\[00;35m\]\h\[\033\[00;32m\](\[\033\[01;35m\]\W\[\033\[01;32m\])\[\033\[00;32m\]\$";
else echo -n "\[\033\[00;35m\]\u\[\033\[01;31m\]@\[\033\[00;35m\]\h\[\033\[01;31m\](\[\033\[35m\]\W\[\033\[31m\])\[\033\[00;31m\]\$";
fi`\[\033\[0m\]'
Upvotes: 0
Reputation: 1169
The problem in your code is that that your quotation is broken:
export PROMPT_COMMAND="
PS1='`
if [ $? -eq 0 ];
then echo '
Generally it should work, try this:
PS1='`if [ $? -eq 0 ] ; then echo Y:; else echo N:; fi`
Here is the output after applying the code:
$ PS1='`if [ $? -eq 0 ] ; then echo Y:; else echo N:; fi`' Y: Y: Y: Y:false N: N: N:true Y: Y:
Note: Simply pressing the ENTER key, doesn't change the prompt.
Upvotes: 4