Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [Bug] Exiting shell from function called by trap handler always produces status 0



On Mon, 2018-10-08 at 14:02 +0100, Martijn Dekker wrote:
> When a trap handler exits the shell using the 'exit' command within a 
> function, the shell's exit status is zero even if another exit status 
> was given as an argument to the 'exit' command.
> 
> $ Src/zsh -c 'fn() { exit 13; }; trap "fn" EXIT'
> $ echo $?
> 0
> (expected output: 13)

diff --git a/Src/builtin.c b/Src/builtin.c
index c5b319b..b81acdb 100644
--- a/Src/builtin.c
+++ b/Src/builtin.c
@@ -5709,7 +5709,13 @@ int shell_exiting;
 mod_export void
 zexit(int val, int from_where)
 {
-    /* Don't do anything recursively:  see below */
+    static int exit_val;
+    /*
+     * Don't do anything recursively:  see below.
+     * Do, however, update exit status --- there's no nesting,
+     * a later value always overrides an earlier.
+     */
+    exit_val = val;
     if (shell_exiting == -1)
 	return;
 
@@ -5757,7 +5763,7 @@ zexit(int val, int from_where)
 #endif
 	}
     }
-    lastval = val;
+    lastval = exit_val;
     /*
      * Now we are committed to exiting any previous state
      * is irrelevant.  Ensure trap can run.
@@ -5771,9 +5777,9 @@ zexit(int val, int from_where)
        release_pgrp();
     }
     if (mypid != getpid())
-	_exit(val);
+	_exit(exit_val);
     else
-	exit(val);
+	exit(exit_val);
 }
 
 /* . (dot), source */
diff --git a/Test/C03traps.ztst b/Test/C03traps.ztst
index dce263f..3b5d4c6 100644
--- a/Test/C03traps.ztst
+++ b/Test/C03traps.ztst
@@ -863,6 +863,9 @@ F:Must be tested with a top-level script rather than
source or function
 >a
 >b
 
+  $ZTST_testdir/../Src/zsh -fc 'fn() { exit 13; }; trap fn EXIT; exit'
+13:Explicit exit in exit trap overrides status
+
 %clean
 
   rm -f TRAPEXIT



Messages sorted by: Reverse Date, Date, Thread, Author