I've encountered a strange (to me) problem in Cygwin bash version 4.3.42(4). Shell variables that are declared in a called script do not persist in the calling script when the former is called from within a function.
I have the following two scripts to illustrate the issue. script1.sh calls script2.sh which sets two variables. If script2 is invoked via a function in script1, the variables are lost, whereas if script2 is invoked without the function call, the variables persist as expected. All invocations of script2 are done via "source".
script1.sh:
#!/usr/bin/bash
#
# calling script
#
function sourceit()
{
source scripts/script2.sh
}
sval=1
echo "$0 before sourceit(); rval=$rval sval=$sval PID=$$"
sourceit
echo "$0 after sourceit(); rval=$rval sval=$sval PID=$$"
sval=3
echo "$0 before source; rval=$rval sval=$sval PID=$$"
source scripts/script2.sh
echo "$0 after source; rval=$rval sval=$sval PID=$$"
script2.sh
#!/usr/bin/bash
#
# called script
#
echo "$0 before declare; rval=$rval sval=$sval PID=$$"
sval=2
declare -r rval=2
echo "$0 after declare; rval=$rval sval=$sval PID=$$"
The results:
scripts/script1.sh before sourceit(); rval= sval=1 PID=1752
scripts/script1.sh before declare; rval= sval=1 PID=1752
scripts/script1.sh after declare; rval=2 sval=2 PID=1752
scripts/script1.sh after sourceit(); rval= sval=2 PID=1752
scripts/script1.sh before source; rval= sval=3 PID=1752
scripts/script1.sh before declare; rval= sval=3 PID=1752
scripts/script1.sh after declare; rval=2 sval=2 PID=1752
scripts/script1.sh after source; rval=2 sval=2 PID=1752
I don't see any subshells being created (the same PID is shown everywhere).
Am I missing a finer point of bash scripting?
Am I missing a finer point?Probably yes. Sourcing the script does not create a new shell and thus the PID stays the same.