LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash; terminate sourced script without closing its shell (https://www.linuxquestions.org/questions/programming-9/bash%3B-terminate-sourced-script-without-closing-its-shell-4175416148/)

ntubski 07-13-2012 12:39 PM

Quote:

Originally Posted by porphyry5 (Post 4725133)
What command within a sourced script will stop execution and return to it's shell's command prompt?

You can use return for this.

Quote:

return
return [n]
Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source.


David the H. 07-13-2012 12:39 PM

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.

Code:

saveenv(){
        declare > file.txt
        exit $1
}

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. :()


All times are GMT -5. The time now is 04:52 PM.