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 | neverI 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
Uh oh!
There was an error while loading. Please reload this page.
-
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
sourced.Here's a suggestion (the explanation for the
is_sourceddetection 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
.shfiles 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
sourceother files, as they all are going to be merged into the single generated script.Being able to
sourcethe 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
sourcemy code in a new bash session and test my functions interactively (kinda like arails consolesession)explaining the
is_sourcedsolutionThis technique was taken from this StackOverflow answer.
The
returnhelp message explains most of what's happening:But let's elaborate it...
Bash allows
returnstatements only from functions and, in a script's top-level scope, only if the script is sourced. Ifreturnis 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):returnin a subshellThe use of a
(parenteses)to create a subshell is necessary, because executingreturnin the top-level scope of a sourced script would exit the script.We need to explicitly use
0as 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