I have a bash script that generates a report on the progress of some long-running jobs on the machine. Basically, this parent script loops through a list of child scripts (calling them all with
source). The child scripts are expected to set a couple of specific variables, which the parent script will then make use of.
Today, I discovered a bug where, a variable set by the first child script accidentally got used by the second child script, causing incorrect output. Is there a clean way to prevent these types of bugs from happening?
Basically, when I
source a child script, there are a couple of specific variables that I want to persist back to the parent script. My parent script resets these specific variables before it
sources each new child script, so there are no issues with them. However, some child scripts may have additional arbitrary variables that it uses locally that should not persist back to the parent script.
Obviously I could manually unset each of these at the end of the child script, but these seems prone to error if I forget one. Is there a more proper way of sourcing a script, and having only certain variables persist to the script that called
edit: For sake of clarity, here's a sort of dumbed down version of my parent script:
echo "<html><body><h1>My jobs</h1>" FILES=~/confs/*.sh for f in $FILES; do # reset variables name="Unnamed job" secsSinceActive="Unknown" statusText="Unknown" # run the script that checks on the job source "$f" # print bit of report echo "<h3>$name</h3>" echo "<p>Last active: $secsSinceActive seconds ago</p>" echo "<p>Status: $statusText</p>" echo "</body></html>"
And here's what one of the child scripts might look like:
name="My awesome job" nowTime=`expr $(date +%s) ` lastActiveTime=`expr $(date +%s -r ~/blah.log)` secsSinceActive=`expr $nowTime - $lastActiveTime` currentRaw=$(cat ~/blah.log | grep "Progress" | tail -n 1) if [ -z "$currentRaw" ]; then statusText="Not running" else statusText="In progress" fi
The variables $name, $secsSinceActive, and $statusText need to persist back to the parent script, but all the other variables should disappear when the child script terminates.