chinmay chhajed
Posted on February 20, 2021
Whenever we execute a shell command, it returns an integer value. When this value is 0
, last command was a success. Any other number is the error code. We can see the return of last command by printing the value of ?
variable.
To test this:
- Enter command
ls
- Check it's return by command
echo $?
- Enter some random letters and press Enter
- Check return by
echo $?
You should get an error in the second time when you enter some random command
chinmay@CC-T480:~/Desktop$ ls
file
chinmay@CC-T480:~/Desktop$ echo $?
0 <-- Success
chinmay@CC-T480:~/Desktop$ a
a: command not found
chinmay@CC-T480:~/Desktop$ echo $?
127 <-- Error code
We will use this $?
value in our prompt to see if our last command has passed or failed.
We also need to know about environment variable PROMPT_COMMAND
. Bash provides an environment variable called PROMPT_COMMAND
. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.
Since our bash prompt should contain status of last command, it should be set inside PROMPT_COMMAND
.
First we will write a simple shell function to update the prompt with return code.
exit_code() {
# Save the exit status of last command. This
# needs to be done first otherwise exit status of
# other commands will be stored in this variable.
EXIT="$?"
# PS1 needs to be reset or else it will
# be appended every time to previous one.
PS1=""
# This will be final prompt, whatever set earlier will be
# overwritten by this.
export PS1="$EXIT \w $ "
}
Then we can add this function to our PROMPT_COMMAND
# exit_code Should be first command in `PROMPT_COMMAND' to be executed or # else return status will always be 0/true as it will hold return status of
# previous command.
# First we check if prompt command is empty or not.
# If empty, just add `exit_code' to it. If non empty,
# make it `exit_code:$PROMPT_COMMAND'
[ -n "$PROMPT_COMMAND" ] && PROMPT_COMMAND="exit_code;$PROMPT_COMMAND" ||
PROMPT_COMMAND="exit_code"
After adding the above 2 snippets in your .bashrc
, you get something like this:
chinmay@CC-T480:~$ exit_code() {
> EXIT="$?"
> PS1=""
> export PS1="$EXIT \w $ "
> }
chinmay@CC-T480:~$ PROMPT_COMMAND="exit_code"
0 ~ $ ls Desktop/
file
0 ~ $ ^C
130 ~ $ a
a: command not found
127 ~ $ echo $?
127
0 ~ $ echo $? # return of last echo command
0
0 ~ $
Note that the first number in our prompt is the return status of last command. For ls
, we see a 0
as it ran as expected. When I ran command a
, bash threw an error saying command not found
and it's error code is 127
which we can see in next line. For pressing ctrl-c
, we can see error code as 130
.
Checkout designing a minimal bash prompt.
Posted on February 20, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.