You can write a function that returns the status given as argument, or 255
if none given. (I call it ret
as it "returns" its value.)
ret() { return "${1:-255}"; }
and use ret
in place of your call to exit
. This is avoids the inefficiency of creating the sub-shell in the currently accepted answer.
Some measurements.
time bash -c 'for i in {1..10000} ; do (exit 3) ; done ; echo $?'
on my machine takes about 3.5 seconds.
time bash -c 'ret(){ return $1 ; } ; for i in {1..10000} ; do ret 3 ; done ; echo $?'
on my machine takes about 0.051 seconds, 70 times faster. Putting in the default handling still leaves it 60 times faster. Obviously the loop has some overhead. If I change the body of the loop to just be :
or true
then the time is halved to 0.025, a completely empty loop is invalid syntax. Adding ;:
to the loop shows that this minimal command takes 0.007 seconds, so the loop overhead is about 0.018. Subtracting this overhead from the two tests shows that the ret
solution is over 100 times faster.
Obviously this is a synthetic measurement, but things add up. If you make everything 100 times slower than they need to be then you end up with slow systems. 0.0
exec exit 3
is no bueno, I get"exec: exit: not found"
exit_code=3
and eliminate theexit 3
line altogether?$?
variable but doesn't exit this script"?