Like an introduction: if secondary.sh has
functionX(){
...
}
and primary.sh has - source secondary.sh declared - and its own functions, therefore:
# primary.sh content
source secondary.sh
functionA(){
...
}
functionB(){
...
}
According with my understanding it is equivalent to have copied and pasted all the source code of the former into the latter. Therefore:
# primary.sh content
functionX(){
...
}
functionA(){
...
}
functionB(){
...
}
Pls correct me if something it is wrong.
Furthermore the script file is executed within the current shell, any change such as environment variables are affected and reflected in the current shell. Until here I am Ok. Again, pls correct me if something is wrong.
Now, for the same primary.sh script file, but with a different scenario - if it has:
source ${SPECIFIC_PATH}/secondary.sh
functionA(){
...
}
functionB(){
...
}
startPrimary(){
...
SPECIFIC_PATH="/somepath"
...
}
it fails because source is executed because is located at the top but SPECIFIC_PATH was not defined yet.
But if it is changed to:
functionA(){
...
}
functionB(){
...
}
startPrimary(){
...
SPECIFIC_PATH="/somepath"
...
source ${SPECIFIC_PATH}/secondary.sh
}
It works, because SPECIFIC_PATH was declared and source was executed at demand.
This scenario was covered here - it is very similar:
But - Is it valid?
I am doing this question because my concern is:
If secondary.sh has functions declared and they are practically copied/pasted in primary.sh - In Unix/Linux Shell Script is valid have functions declared within other functions? I hope you see my point. I am assuming is happening the following:
functionA(){
...
}
functionB(){
...
}
startPrimary(){
...
SPECIFIC_PATH="/somepath"
...
functionX(){
...
}
}
sourceisn't a standard, portable command. It is a bash-specific (and some other shells) alias for the standard.command..shfiles, all declared with#! /bin/bash. So is fine use eithersourceor.Is it supposed to source a different secondary script each time?Yes. -but does it actually execute the functions within the sourced file, or just make them available in the calling script?Both