Replies: 3 comments 14 replies
-
Why not this: if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
initialize
run "$@"
fi |
Beta Was this translation helpful? Give feedback.
6 replies
-
Also - if there is a small doubt that some users may want the current behavior - we can add a setting for it, with a sensible default: # settings.yml
enable_sourcing: always # always | production | development | never I feel like this goes well with the What do you think? |
Beta Was this translation helpful? Give feedback.
8 replies
-
Implemented via #597 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Request
The final script finishes with a
run "$@"
and that actually "runs the program".It would be better if that call didn't happen when the script is being
source
d.Here's a suggestion (the explanation for the
is_sourced
detection is at the end of this post):I believe this solution has no effect on the usual way of calling the final script for an actual run, then generating the final code with that logic could be the default behavior. There's not even a need to implement it as a configuration option.
Motivation
The main motivation is because I usually source my
.sh
files with functions in order to "unit test" the functions.It wasn't a problem in my usual workflow, where files sourcing other files is perfectly normal. But with bashly we can't/shouldn't
source
other files, as they all are going to be merged into the single generated script.Being able to
source
the final script without actually running it would solve this problem, as I would be able to "unit test" my functions from there.Another motivation is that sometimes I like to
source
my code in a new bash session and test my functions interactively (kinda like arails console
session)explaining the
is_sourced
solutionThis technique was taken from this StackOverflow answer.
The
return
help message explains most of what's happening:But let's elaborate it...
Bash allows
return
statements only from functions and, in a script's top-level scope, only if the script is sourced. Ifreturn
is used out of these conditions, it fails (non-zero exit code) and an error message is emitted.Let's check what happens in an interactive session.
Explaining the
(return 0 2>/dev/null)
:return
in a subshellThe use of a
(
parenteses)
to create a subshell is necessary, because executingreturn
in the top-level scope of a sourced script would exit the script.We need to explicitly use
0
as the return operand, because omitting it can produce incorrect result if the last command on the user's shell has a non-zero return value.Beta Was this translation helpful? Give feedback.
All reactions