Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include non-0 exit codes in the subsequent bash prompt

Occasionally, I will run a command that has a lot of output. Occasionally, the last 30-40 lines of that output (a.k.a. the only part of the output I ever really see) is fine, but much further up, there was an error. I'd like to make it easier to notice that the command failed. To do so, I want the return code to be part of my prompt. So I took my $PS1:

[\D{%Y-%m-%d} \t] \[\e]0;\u@\h: \w\a\]\$

...and extended it to this:

[\D{%Y-%m-%d} \t] ${?/^0$/} \[\e]0;\u@\h: \w\a\]\$

This results in a prompt like this:

[2011-05-10 09:38:07] 0 soren@lenny:~$ 

However, I'd like to find a way to have it only include the exit code if it was non-0. How can I do that? Sure, I could use

$(echo \$? | sed -e blah)

but as lightweight as sed is, it's still quite a bit more heavy weight than bash's builtin stuff.

like image 718
Soren Avatar asked May 10 '11 07:05

Soren


People also ask

What is a non-zero exit code?

A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so there is one well-defined way to indicate success and a variety of ways to indicate various failure modes. When a command terminates on a fatal signal whose number is N , Bash uses the value 128+ N as the exit status.

What is exit code 0 bash?

For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.

How do I get the exit code in last command bash?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.

How do I find exit code in bash?

Checking Bash Exit Code Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.


1 Answers

A little bit of printf abuse:

printf '%.*s' $? $?
like image 68
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 12:10

Ignacio Vazquez-Abrams