I want to display a green smile face if the previous exit code is 0 and red smile face if not successful.
Basically I want to do this prompt but with other stuff in
I assume your quoting is not correct. I fiddled a little bit around with this and finally got it working:
$ bash --version
GNU bash, version 4.4.12(3)-release (i686-pc-cygwin)
$ smiley()
> {
> if [ "$?" == "0" ]; then
> echo -e '\e[0;32m:) '
> else
> echo -e '\e[0;31m:( '
> fi
> }
$ PS1="$PS1"'`smiley`'
$ :) rm non-existing
rm: cannot remove 'non-existing': No such file or directory
$ :( echo "Everything fine"
Everything fine
$ :)
I did this on Windows (64 bit) but I guess it should work on Linux (or any other Unix-like) as well.
Notes:
I wrote a function smiley()
(a simplified version of your) and checked it by calling it from command line. It worked fine.
I added it to PS1
and it echoed :)
in any case. I realized that the bash replacement was already done in assignment of PS1
.
Thus, I safed the invocation of smiley
by an extra pair of single quotes to defer the invocation until the output of prompt. Now, it works like expected.
Because the questioner required a colored version I made an update. I found the actual solution in this link: SO: How to change the output color of echo in Linux. It's easy to find the necessary terminal escape sequences. The trick is to use echo -e
to enable the backslash escaping in echo
.
The snapshot below shows how does it look (with colors):