[Gllug] show non-zero exit code in bash

Tethys sta296 at astradyne.co.uk
Wed Dec 28 18:21:04 UTC 2005


salsaman writes:

>PROMPT_COMMAND='ret=$?; [ "x$ret" == "x0" ] || echo latest exit code $ret;'

Errr... no. Try pressing return a few times after you've run a command
with a non-zero exit code. You need to keep track of the fact that you've
already printed the exit code. What you want is something like:

	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
	}

	export PROMPT_COMMAND=show_exit_code

This also handles the corner cases:

- Successive commands with non-zero exit codes
- "Null commands", i.e., pressing return at the shell prompt

Easy enough, but it would be nice to have some zsh-like syntactic
sugar to do this. Also, the use of history is a bit of a kludge.
I was sure there was some built in shell variable to return the
event number of the last command executed, but I can't find it in
the man page.

Tet
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list