📄 localvar.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Local Variables</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Functions"HREF="functions.html"><LINKREL="PREVIOUS"TITLE="Functions"HREF="functions.html"><LINKREL="NEXT"TITLE="Recursion Without Local Variables"HREF="recurnolocvar.html"><METAHTTP-EQUIV="Content-Style-Type"CONTENT="text/css"><LINKREL="stylesheet"HREF="common/kde-common.css"TYPE="text/css"><METAHTTP-EQUIV="Content-Type"CONTENT="text/html; charset=iso-8859-1"><METAHTTP-EQUIV="Content-Language"CONTENT="en"><LINKREL="stylesheet"HREF="common/kde-localised.css"TYPE="text/css"TITLE="KDE-English"><LINKREL="stylesheet"HREF="common/kde-default.css"TYPE="text/css"TITLE="KDE-Default"></HEAD><BODYCLASS="SECT1"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLESUMMARY="Header navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><THCOLSPAN="3"ALIGN="center">Advanced Bash-Scripting Guide: An in-depth exploration of the art of shell scripting</TH></TR><TR><TDWIDTH="10%"ALIGN="left"VALIGN="bottom"><AHREF="functions.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 23. Functions</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="recurnolocvar.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="LOCALVAR"></A>23.2. Local Variables</H1><DIVCLASS="VARIABLELIST"><P><B><ANAME="LOCALREF1"></A>What makes a variable <ICLASS="FIRSTTERM">local</I>?</B></P><DL><DT>local variables</DT><DD><P>A variable declared as <ICLASS="FIRSTTERM">local</I> is one that is visible only within the <AHREF="special-chars.html#CODEBLOCKREF">block of code</A> in which it appears. It has local <SPANCLASS="QUOTE">"scope."</SPAN> In a function, a <ICLASS="FIRSTTERM">local variable</I> has meaning only within that function block.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX62"></A><P><B>Example 23-12. Local variable visibility</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # Global and local variables inside a function. 3 4 func () 5 { 6 local loc_var=23 # Declared as local variable. 7 echo # Uses the 'local' builtin. 8 echo "\"loc_var\" in function = $loc_var" 9 global_var=999 # Not declared as local. 10 # Defaults to global. 11 echo "\"global_var\" in function = $global_var" 12 } 13 14 func 15 16 # Now, to see if local variable "loc_var" exists outside function. 17 18 echo 19 echo "\"loc_var\" outside function = $loc_var" 20 # $loc_var outside function = 21 # No, $loc_var not visible globally. 22 echo "\"global_var\" outside function = $global_var" 23 # $global_var outside function = 999 24 # $global_var is visible globally. 25 echo 26 27 exit 0 28 # In contrast to C, a Bash variable declared inside a function 29 #+ is local *only* if declared as such.</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="CAUTION"><TABLECLASS="CAUTION"WIDTH="90%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/caution.png"HSPACE="5"ALT="Caution"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>Before a function is called, <SPANCLASS="emphasis"><ICLASS="EMPHASIS">all</I></SPAN> variables declared within the function are invisible outside the body of the function, not just those explicitly declared as <ICLASS="FIRSTTERM">local</I>. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 func () 4 { 5 global_var=37 # Visible only within the function block 6 #+ before the function has been called. 7 } # END OF FUNCTION 8 9 echo "global_var = $global_var" # global_var = 10 # Function "func" has not yet been called, 11 #+ so $global_var is not visible here. 12 13 func 14 echo "global_var = $global_var" # global_var = 37 15 # Has been set by function call.</PRE></TD></TR></TABLE> </P></TD></TR></TABLE></DIV></DD></DL></DIV><DIVCLASS="SECT2"><H2CLASS="SECT2"><ANAME="LOCVARRECUR"></A>23.2.1. Local variables and recursion.</H2><P><ANAME="RECURSIONREF0"></A></P><TABLECLASS="SIDEBAR"BORDER="1"CELLPADDING="5"><TR><TD><DIVCLASS="SIDEBAR"><ANAME="AEN17125"></A><P><ANAME="RECURSIONREF"></A></P><P><ICLASS="FIRSTTERM">Recursion</I> is an interesting and sometimes useful form of <ICLASS="FIRSTTERM">self-reference</I>. <AHREF="biblio.html#MAYERREF">Herbert Mayer</A> defines it as <SPANCLASS="QUOTE">". . . expressing an algorithm by using a simpler version of that same algorithm . . ."</SPAN></P><P>Consider a definition defined in terms of itself, <ANAME="AEN17134"HREF="#FTN.AEN17134">[1]</A> an expression implicit in its own expression, <ANAME="AEN17137"HREF="#FTN.AEN17137">[2]</A> <SPANCLASS="emphasis"><ICLASS="EMPHASIS">a snake swallowing its own tail</I></SPAN>, <ANAME="AEN17141"HREF="#FTN.AEN17141">[3]</A> or . . . a function that calls itself. <ANAME="AEN17144"HREF="#FTN.AEN17144">[4]</A> </P><P><ANAME="RECURSIONDEMO0"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="RECURSIONDEMO"></A><P><B>Example 23-13. Demonstration of a simple recursive function</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 # recursion-demo.sh 3 # Demonstration of recursion. 4 5 RECURSIONS=9 # How many times to recurse. 6 r_count=0 # Must be global. Why? 7 8 recurse () 9 { 10 var="$1" 11 12 while [ "$var" -ge 0 ] 13 do 14 echo "Recursion count = "$r_count" +-+ \$var = "$var"" 15 (( var-- )); (( r_count++ )) 16 recurse "$var" # Function calls itself (recurses) 17 done #+ until what condition is met? 18 } 19 20 recurse $RECURSIONS 21 22 exit $?</PRE></TD></TR></TABLE><HR></DIV></DIV></TD></TR></TABLE><P>Local variables are a useful tool for writing recursive code, but this practice generally involves a great deal of computational overhead and is definitely <SPANCLASS="emphasis"><ICLASS="EMPHASIS">not</I></SPAN> recommended in a shell script. <ANAME="AEN17154"HREF="#FTN.AEN17154">[5]</A> </P><P><ANAME="FACTORIALREF"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="EX63"></A><P><B>Example 23-14. Recursion, using a local variable</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 # factorial 4 # --------- 5 6 7 # Does bash permit recursion? 8 # Well, yes, but... 9 # It's so slow that you gotta have rocks in your head to try it. 10 11 12 MAX_ARG=5 13 E_WRONG_ARGS=65 14 E_RANGE_ERR=66 15 16 17 if [ -z "$1" ] 18 then 19 echo "Usage: `basename $0` number" 20 exit $E_WRONG_ARGS 21 fi 22 23 if [ "$1" -gt $MAX_ARG ] 24 then 25 echo "Out of range (5 is maximum)." 26 # Let's get real now. 27 # If you want greater range than this, 28 #+ rewrite it in a Real Programming Language. 29 exit $E_RANGE_ERR 30 fi 31 32 fact () 33 { 34 local number=$1 35 # Variable "number" must be declared as local, 36 #+ otherwise this doesn't work. 37 if [ "$number" -eq 0 ] 38 then 39 factorial=1 # Factorial of 0 = 1. 40 else 41 let "decrnum = number - 1" 42 fact $decrnum # Recursive function call (the function calls itself). 43 let "factorial = $number * $?" 44 fi 45 46 return $factorial 47 } 48 49 fact $1 50 echo "Factorial of $1 is $?." 51 52 exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Also see <AHREF="contributed-scripts.html#PRIMES">Example A-16</A> for an example of recursion in a script. Be aware that recursion is resource-intensive and executes slowly, and is therefore generally not appropriate in a script.</P></DIV></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN17134"HREF="localvar.html#AEN17134">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Otherwise known as <ICLASS="FIRSTTERM">redundancy</I>.</P></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN17137"HREF="localvar.html#AEN17137">[2]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Otherwise known as <ICLASS="FIRSTTERM">tautology</I>.</P></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN17141"HREF="localvar.html#AEN17141">[3]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Otherwise known as a <ICLASS="FIRSTTERM">metaphor</I>.</P></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN17144"HREF="localvar.html#AEN17144">[4]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Otherwise known as a <ICLASS="FIRSTTERM">recursive function</I>.</P></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN17154"HREF="localvar.html#AEN17154">[5]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Too many levels of recursion may crash a script with a segfault. <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING"> 1 #!/bin/bash 2 3 # Warning: Running this script could possibly lock up your system! 4 # If you're lucky, it will segfault before using up all available memory. 5 6 recursive_function () 7 { 8 echo "$1" # Makes the function do something, and hastens the segfault. 9 (( $1 < $2 )) && recursive_function $(( $1 + 1 )) $2; 10 # As long as 1st parameter is less than 2nd, 11 #+ increment 1st and recurse. 12 } 13 14 recursive_function 1 50000 # Recurse 50,000 levels! 15 # Most likely segfaults (depending on stack size, set by ulimit -m). 16 17 # Recursion this deep might cause even a C program to segfault, 18 #+ by using up all the memory allotted to the stack. 19 20 21 echo "This will probably not print." 22 exit 0 # This script will not exit normally. 23 24 # Thanks, St閜hane Chazelas.</PRE></TD></TR></TABLE></P></TD></TR></TABLE><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLESUMMARY="Footer navigation table"WIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="functions.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html"ACCESSKEY="H">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="recurnolocvar.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Functions</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="functions.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Recursion Without Local Variables</TD></TR></TABLE></DIV></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -