Bash – Last exit status from within script without source

bashshell-script

Supposing someone invokes a non-existent command, the only way I know to retrieve its error status from a script I execute right after is by using source

I.e., let's say this script's name is dummy where its contents are simply

#!/bin/bash

echo $?

I know I will only get the exit status I'm looking for (127) if I invoke source dummy, but is there another way to facilitate getting the exit status (preferably without using alias) from the last command from within the script, without using source so I could simply call dummy to get my desired behaviour?

I am simply trying to make a script to check for a typo in the previous command. This requires detecting the previous exit status to make sure there was a potential typo in the first place, so I need to be able to get the exit status of the last command from within the script. I am also hoping to minimize the amount of setup a user would have to do, so that a user could simple invoke dummy, for example, and the rest would be taken care of. This is my reason for trying to avoid source or ., or alias.

My initial test for exit status of the last command was to use

#!/bin/bash
ESTATUS=$? # Saved exit status for later
echo $ESTATUS

but this required having to run that script with source. Is there a good way to replicate this without having to use source, or .?

Best Answer

I'm not quite sure where that will lead to, but you can do:

alias dummy='sh dummy $?'
the_program_with_errors
dummy

and your dummy script would contain:

echo $1

An approach without alias is to use a shell function:

function dummy { sh dummy $? ;}

With that definition you can get the following behaviour (simulated with true, false, and a subshell process):

$ true 
$ dummy
0
$ false
$ dummy
1
$ (exit 42)
$ dummy    
42
Related Question