fork download
  1. #!/usr/bin/env bash
  2. # dynamic_scope_demo_fixed.sh
  3.  
  4. ############################
  5. # global variables (all start at 0)
  6. ############################
  7. a=0; b=0; c=0; d=0
  8.  
  9. ############################
  10. # g1, g2, g3
  11. ############################
  12. g1 () { # g1(int b ; int c)
  13. local b=$1 c=$2
  14. printf '%d %d %d %d\n' "$a" "$b" "$c" "${d:-0}"
  15. }
  16.  
  17. g2 () { # g2(int a ; int c)
  18. local a=$1 c=$2
  19. g1 "$a" "$c"
  20. }
  21.  
  22. g3 () { # g3(int c ; int a)
  23. local c=$1 a=$2
  24. local b=3
  25. g1 "$a" "$b" # line 1
  26.  
  27. ( # --- begin inner block in a *sub-shell*
  28. local c=8
  29. local d=4
  30. g2 "$a" "$b" # line 2 (d == 4 is visible here)
  31. ) # --- end inner block (d & c disappear)
  32.  
  33. g1 "$a" "$b" # line 3 (d fell back to global 0)
  34. printf '%d\n' "$b" # “return” value
  35. }
  36.  
  37. ############################
  38. # main
  39. ############################
  40. main () {
  41. local a=4
  42. local b=5
  43. a=$(g3 "$b" "$c") # c == 0 (global)
  44. g3 "$b" "$a"
  45. }
  46.  
  47. main
  48.  
Success #stdin #stdout #stderr 0.01s 5316KB
stdin
Standard input is empty
stdout
0 0 3 0
0 0 3 4
0 0 3 0
3
stderr
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number
prog.pl: line 14: printf: 0 0 3 0
0 0 3 4
0 0 3 0
3: invalid number