Glad I could be of service.
I was thinking though that it would be more robust to set it up as a trap
. That way it will print the output whenever the script fails or is manually terminated as well.
declare > file.txt
trap 'saveenv $?' INT TERM EXIT
You can modify the function to include other commands too, of course.
The hard quotes around the trap
command ensure that the exit code of the final command to run gets passed to the function, and therefore preserved as the script's exit code. Double-quotes would expand the value at the time the trap is set up instead, and you'd (probably) always get 0.
(Edit: Sheesh! Between the time I opened the page and the time I posted, there've been 3 posts. Kinda confuses the context of what I was replying to. Sorry.