27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

{<br />

local loc_var=23 # Declared local.<br />

echo<br />

echo "\"loc_var\" in function = $loc_var"<br />

global_var=999<br />

# Not declared local.<br />

echo "\"global_var\" in function = $global_var"<br />

}<br />

func<br />

# Now, see if local 'a' exists outside function.<br />

echo<br />

echo "\"loc_var\" outside function = $loc_var"<br />

# "loc_var" outside function =<br />

# Nope, $loc_var not visible globally.<br />

echo "\"global_var\" outside function = $global_var"<br />

# "global_var" outside function = 999<br />

# $global_var is visible globally.<br />

echo<br />

exit 0<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

Before a function is called, all variables declared within the function are invisible outside the<br />

body of the function, not just those explicitly declared as local.<br />

#!/bin/bash<br />

func ()<br />

{<br />

global_var=37<br />

# Visible only within the function block<br />

#+ before the function has been called.<br />

} # END OF FUNCTION<br />

echo "global_var = $global_var" # global_var =<br />

# Function "func" has not yet been called,<br />

#+ so $global_var is not visible here.<br />

func<br />

echo "global_var = $global_var" # global_var = 37<br />

# Has been set by function call.<br />

23.2.1. Local variables make recursion possible.<br />

Local variables permit recursion, [53] but this practice generally involves much computational overhead and<br />

is definitely not recommended in a shell script. [54]<br />

Example 23−9. Recursion, using a local variable<br />

#!/bin/bash<br />

# factorial<br />

# −−−−−−−−−<br />

# Does bash permit recursion?<br />

# Well, yes, but...<br />

Chapter 23. Functions 284

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!