[Gllug] show non-zero exit code in bash
Greater London Linux User Group
gllug at gllug.org.uk
Thu Dec 29 13:18:56 UTC 2005
Dean Wilson <dwilson at unixdaemon.net> writes:
> On Wed, Dec 28, 2005 at 06:21:04PM +0000, Tethys wrote:
>> show_exit_code()
>> {
>> retval=$?
>> cmdnum="$(history 1 | sed 's/\(^[0-9 ]*\).*/\1/')"
>> if [ $retval -ne 0 -a "$cmdnum" != "$lastcmdnum" ]
>> then
>> lastcmdnum="$cmdnum"
>> echo "Exit code: $retval"
>> fi
>> }
>
> show_exit_code() {
> retval=$?
> if [ $retval -ne 0 -a "$HISTCMD" != "$lastcmdnum" ];then
> lastcmdnum="$HISTCMD"
> echo " -- exit code: $retval"
> fi
> }
>
> I've tweaked it a bit (and reformatted it to suit my .bash_profile) and
> by using $HISTCMD I can drop the two external commands
>
>> This also handles the corner cases:
>> - Successive commands with non-zero exit codes
>> - "Null commands", i.e., pressing return at the shell prompt
>
> Which is what my initial version failed to deal with.
>
> A pint is yours to claim Mr Tethys!
This still doesn't quite work. It solves the mentioned cases but adds
one of its own, namely that if you run the same command again and again
(after recompiling elsewhere, for example) HISTCMD is not updated, even
if you don't set HISTCONTROL to ignoredups. The solution to this is to
return to the former, only you can lose the sed thusly:
show_exit_code() {
retval=$?
cmdnum="$(history 1)"
cmdnum=$((${cmdnum:0:5}))
if [ $retval -ne 0 -a "$cmdnum" != "$lastcmdnum" ]; then
lastcmdnum="$cmdnum"
echo -e "\033[1;31mCommand ($cmdnum) failed with exit code:" \
"\033[1;35m$retval\033[0m"
fi
}
Incidentally you can do some very cool stuff with the $ symbol - search
for Parameter Expansion in the bash manpage.
This also solves the other corner case of it not being colourful :-)
Unfortunately, though, it won't work if you have history control set to
ignoredups, so it's still not perfect.
And I can't to find a way to reduce the two cmdnum= lines to one.
Matthew
--
I must take issue with the term "a mere child," for it has been my
invariable experience that the company of a mere child is infinitely
preferable to that of a mere adult.
-- Fran Lebowitz
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 194 bytes
Desc: not available
URL: <http://mailman.lug.org.uk/pipermail/gllug/attachments/20051229/7a17b213/attachment.pgp>
-------------- next part --------------
--
Gllug mailing list - Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug
More information about the GLLUG
mailing list