I am using a Mac and I want to be able to show emoji X for every successful command that I type in and emoji Y for every command that results in failure.
Asked
Active
Viewed 895 times
2
-
1Which shell are you using? This is facile to achieve in zsh. – Sparhawk Dec 09 '18 at 00:05
-
bash, whatever is standard on mac. – eugenekgn Dec 09 '18 at 02:28
-
While technically OSX is based on Linux, there's an active Mac-specific SE site and this question is much more appropriate there. You'd get better answers as well. – Bagalaw Dec 09 '18 at 03:24
-
2@Bagalaw I disagree. This is a purely bash question, and IMO appropriate for U/L. – Sparhawk Dec 09 '18 at 03:40
-
@eugenekgn There are numerous similar questions on this site. Have a look and see if you can work it out from them. – Sparhawk Dec 09 '18 at 03:41
1 Answers
6
Bash has some variables that let you control the prompt:
PROMPT_COMMAND
PS1
PS2
PS3
PS4
In this specific scenario, only PROMPT_COMMAND
(code executed before printing the primary prompt) and PS1
(the primary prompt) are helpful.
And the variable ?
let you know the exit status of the last command executed. For example:
command
if [[ "${?}" == '0' ]]; then
echo 'OK'
else
echo 'ERROR'
fi
So you just need to take advantage of these handy features:
# Using PROMPT_COMMAND
PROMPT_COMMAND='if [[ "${?}" == "0" ]]; then printf "[OK]"; else printf "[ERROR]"; fi'
# Using PS1
PS1='$(if [[ "${?}" == "0" ]]; then printf "[OK]"; else printf "[ERROR]"; fi)\$ '
Both ways would print something like this (assuming your initial prompt is $
):
[OK]$ false
[ERROR]$ true
[OK]$
Just replace [OK]
and [ERROR]
with your desired emojis.
You can read the Controlling the Prompt section of Bash manual to learn more about this topic.

nxnev
- 3,654
-
Most people just say
"$?"
. I see no reason to include the{
and the}
; do you have one? – G-Man Says 'Reinstate Monica' Dec 09 '18 at 05:42 -
@G-Man It's just my personal preference. Neither the braces nor the quotes around
${?}
are really needed in that case AFAIK. – nxnev Dec 09 '18 at 06:10 -
Well, quoting shell variables is always recommended; see Security implications of forgetting to quote a variable in bash/POSIX shells, including Steven Penny's answer. My answer to another question is also relevant. – G-Man Says 'Reinstate Monica' Dec 09 '18 at 06:27
-
@G-Man Sorry, I didn't express myself correctly. What I meant is that there's no need to quote the
${?}
in[[ "${?}" == "0" ]]
because word splitting doesn't affect such variable in that specific case. I quoted it anyway because, as Stéphane Chazelas said in the question you linked, "omitting quotes [...] can send a wrong message to beginners: that it may be all right not to quote variables". For the record, I've also made an answer about some subtleties of word splitting. – nxnev Dec 09 '18 at 07:30