I use a script that extends using the bash source feature;
#!/bin/bash
source someneatscriptthatendsprematurely.sh
I would like to be able to return from that script, without breaking the main script.
Using exit breaks the main script, return is only valid in functions and experimenting with $(exit 1) does not seem to work either.
So, is it possible to return in a sub-bash script without breaking the main bash?
Any help appreciated!
I had the same problem just now
I realized that adding a checker function and returning that will not also return the function on its caller for example.
On bash_functions
What happens here is since the checkers is the only place its returned so install_packer_linux will still continue
So you can do two things here. Either keep the current format (function calling another function) as is and evaluate using truthy value then return if the values are not truthy or rewrite the checker on the main installer_packer_linux function
Truthy:
Notice we added || return after the checks and concatenated the checks using && so if not both checks are truthy we return the function
You need the
return
statement:You can see this in action with the following two scripts:
When you run
script1.sh
, you see:Is it important that you can change environment variables? Since otherwise you can just execute the script by executing it without source: