简体   繁体   中英

Capturing the exit code of sourced shell script without invoking subshell

I have two shell scripts:

test.sh

function func() {
echo $1
exit 1
}

run.sh

source ./test.sh

func "Hello"
exitCode=$?
echo "Output: ${exitCode}"

Result:

Hello

The current problem which I'm facing is that when the function func returns 1, my run.sh script breaks and nothing gets executed after it. So, is there any way I can effectively capture the exit code without breaking run.sh. I know there is way to invoke a subshell using ( func "Hello" ) but I want to do it without invoking sub-shell using flock. I looked up for reference example but could'nt find any close to it.

2 ideas that are "pushing the boundary". Use with care , as future changes to the sourced script(s) might break the logic. Recommended only if there is a way to monitor that script is working OK - eg when executing interactively, etc.

I would not use this kind of solutions in any production/critical system.

Option 1: Alias 'exit' to 'return' when sourcing the file.

Assuming that ALL 'exit' statement in the test.sh are to be replaced with 'return', and assuming that you are willing to take the risk of future changes to test.sh, consider using alias before sourcing

alias exit=return
source test.sh
unalias exit
func "foo"

Option 2: automatically update the function that is using 'exit' to use return.

source test.sh
body=$(type func | tail +2 | sed -e 's/exit/return/g')
eval "$body"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM