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.
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.
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.
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.
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.
A little bit of printf
abuse:
printf '%.*s' $? $?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With