Display emoji faces for correct & wrong commands in terminals

Building on Maghin's post.

# Use echo -n to leave out the line end.
# Use -C option with hexdump to avoid big endian/little 
# endian confusion.
mac $  echo -n 😀 | hexdump -C
00000000  f0 9f 98 80                                       |....|
00000004
mac $  echo -n 😱  | hexdump -C
00000000  f0 9f 98 b1                                       |....|
00000004

"Include non-0 exit codes in the subsequent bash prompt" http://stackoverflow.com/questions/5946873/include-non-0-exit-codes-in-the-subsequent-bash-prompt

Here is what I ended up with:

export PS1='\u $(highlightExitCode) \$ '


highlightExitCode()
    {
        exit_code=$?
        if [ $exit_code -ne 0 ]
        then
           echo -en '\xf0\x9f\x98\xb1 '
        else
           echo -en '\xf0\x9f\x98\x80 '
        fi

    }

enter image description here

A more straight forward alternative for the highlightExitCode function:

 highlightExitCode ()  { 
   if [ $? -ne 0 ]; then
     echo -n '😱 ';
   else
     echo -n '😀 ';
   fi 
 }

The only problem is that the bad image appears until to you run a succesful command.

enter image description here


You can use the hexadecimal form of the icon.

Here is my method :

Copy an emoji from a graphical source : https://getemoji.com/ Then paste it in your terminal in the following command :

$ echo 😀 | hexdump
0000000 9ff0 8098 000a                         
0000005

Then take every octal and put \x before each :

$ echo -e '\xf0\x9f\x98\x80\x0a\x00'
😀

Y'all, why not leave out the UTF-8 byte stuff and just use the Unicode code point value? This stuff is easier to look up on emojipedia and does not nail you down to a single terminal setting.

__ps1_ret() {
  # Don't pollute the return value in case we use it for something else
  local _r=$?
  if ((_r == 0)); then
    echo -n $'\U1F600' # 😀 Grinning Face, U+1F600
  else
    echo -n $'\U1F631' # 😱 Face Screaming in Fear, U+1F631
  fi
  return "$_r"
}

PS1='$(__ps1_ret)'"$PS1"

This stuff works everywhere with any encoding that knows how to encode these two characters. Yeah, for emoji this would only include the UTFs and the UTF-in-disguise GB18030 encoding, but it is still a way that more easily connects to well-known sources of emoji reference: code points.

(Oh, the $'...' thing is pretty much restricted to cool shells like bash and zsh.)