In a Bash script, how can I exit the entire script

2019-01-12 13:09发布

I'm writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I'll just abort the tests.

Is there a way I can do this without wrapping the entire script inside of a while loop and using breaks? Something like a dun dun dun goto?

7条回答
你好瞎i
2楼-- · 2019-01-12 14:10

If you will invoke the script with source, you can use return <x> where <x> will be the script exit status (use a non-zero value for error or false). This will also work as expected, when you source the script, but if you invoke an executable script (i.e., directly with its filename), the return statement will result in a complain (error message "return: can only `return' from a function or sourced script").

If exit <x> is used instead, when the script is invoked with source, it will result in exiting the shell that started the script, but an executable script will run directly fine.

To handle either case in the same script, you can use

return <x> 2> /dev/null || exit <x>

This will handle whichever invocation may be suitable.

Note: <x> is supposed to be just a number.

查看更多
登录 后发表回答