Skip to content

Instantly share code, notes, and snippets.

@guziy
Last active August 29, 2015 14:07
Show Gist options
  • Save guziy/8a0bf8898cbacb09b56d to your computer and use it in GitHub Desktop.
Save guziy/8a0bf8898cbacb09b56d to your computer and use it in GitHub Desktop.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment