Stand With Ukraine

Thursday, October 9, 2014

Bash background processes, function and local variables example

#!/bin/bash
#This simple code demonstrates how to define a function, local and global variables in bash.
#And most importantly, how to launch background processes and wait for their termination
gvar="Glob value"
ncalls=0
avar="Test"
# Note for ksh users: in ksh to mark a function definition you should use either function keyword
# or () after the function name, not both
function a_proc(){
echo ${gvar}
local avar=$1 #ksh users: use 'typeset' instead of 'local'
echo "Input: ${avar}"
sleep 100
avar=$(date)
echo "Output: ${avar}"
ncalls=$((${ncalls} + 1))
}
a_proc "$(date)" &
a_proc "$(date)" &
a_proc "$(date)" &
a_proc "$(date)" &
a_proc "$(date)" &
a_proc "$(date)" &
wait
#Although I am trying to update ${ncalls} assuming that this will change my global variable, but ...
#This is because I am launching the function in background, which works in a subshell,
#so global variables won't be updated
echo "ncalls=${ncalls}"
echo "avar=${avar}"
##But look what happens with ncalls when launched in foreground
a_proc "$(date)"
echo "ncalls=${ncalls}"
##Conclusion: the local keyword (for bash, use typeset for ksh) can be useful if you want to make sure that you are not
##changing a global variable in your function