macOS Terminal – Using Emoji in bash $PS1 Prompt

bashcommand linemacosterminal

This question is related to
https://apple.stackexchange.com/a/357132/44531

I would like to have a space after the emoj ?. I've tried in the script below but I'm getting two lines instead of the hoped for single line. And, No I do not want two spaces appear in the zero return code case as I coded up in my original answer.

enter image description here

mac RC=1 ?$ declare -f highlightExitCode
highlightExitCode () 
{ 
    exit_code=$?;
    if [ $exit_code -ne 0 ]; then
        echo -en " RC=${exit_code} "'\xf0\x9f\x98\xb1\x0a\x00';
    else
        echo -e "";
    fi
}
mac $ echo $PS1
\u$(highlightExitCode) \$
mac $ 
mac $ er
-bash: er: command not found
mac RC=127 ?$ 
# FYI: I edited out the non-appearing space 
#in my terminal output

I'm running macOS 10.10.5.

 mac RC=127 ?
  $ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)
Copyright (C) 2007 Free Software Foundation, Inc.
mac $ 

When I try to add a space in the code below, I get a new line added.

enter image description here

mac $ echo $PS1
\u$(highlightExitCode) \$
mac $ declare -f highlightExitCode
highlightExitCode () 
{ 
    exit_code=$?;
    if [ $exit_code -ne 0 ]; then
        echo -en " RC=${exit_code} "'\xf0\x9f\x98\xb1\x0a\x00'" ";
    else
        echo -e "";
    fi
}
mac $ error
-bash: error: command not found
mac RC=127 ?
  $ 
mac RC=127 ?
  $ 
mac RC=127 ?
  $ 

——– fyi ————

actually, when I copy and past here I get a space after the emoj, but the space doesn't appear in my mac terminal.

mac RC=127 ? $ 
mac $ 
mac $ 
mac $ 

Best Answer

You can always wrap in additional command substitutions to do this, for eg:

$ printf "%s  <-- some space after it" "$(echo -en " RC=${exit_code} "'\xf0\x9f\x98\xb1\x0a')"
 RC= ?  <-- some space after it

I'm not sure why you have that NUL character (\x00) trailing but with that I was getting this error message:

$ printf "%s  <-- some space after it" "$(echo -en " RC=${exit_code} "'\xf0\x9f\x98\xb1\x0a\x00')"
-bash: warning: command substitution: ignored null byte in input
 RC= ?  <-- some space after it

So I simply removed it.

Here I've wrapped your original echo command in a command substitution $(..command..) and then passed its output to printf to produce any additional formatting.

General structure:

$ printf "%s ...." "$(..command to produce output..)"

Additional Example

You could also use printf exclusively. I'm not entirely sure what your goal is here but you could do something like this:

$ printf "RC=${exit_code} \xf0\x9f\x98\xb1  <-- some space after it\n\n"
RC= ?  <-- some space after it

The UTF-8 code \x0a is a linefeed character, the above example removed it + the NUL, \x00 and added 2 newlines to the end instead, \n\n.