Sample Header Ad - 728x90

Best way to make variables local in a source'd bash script?

18 votes
4 answers
14952 views
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 source? edit: For sake of clarity, here's a sort of dumbed down version of my parent script: echo "

My jobs

" 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 "

$name

" echo "

Last active: $secsSinceActive seconds ago

" echo "

Status: $statusText

" echo "" 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.
Asked by Hayden Schiff (977 rep)
Jul 30, 2015, 06:21 PM
Last activity: May 28, 2025, 07:57 AM