⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 localvar.html

📁 Shall高级编程
💻 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&nbsp;#!/bin/bash   2&nbsp;# Global and local variables inside a function.   3&nbsp;   4&nbsp;func ()   5&nbsp;{   6&nbsp;  local loc_var=23       # Declared as local variable.   7&nbsp;  echo                   # Uses the 'local' builtin.   8&nbsp;  echo "\"loc_var\" in function = $loc_var"   9&nbsp;  global_var=999         # Not declared as local.  10&nbsp;                         # Defaults to global.   11&nbsp;  echo "\"global_var\" in function = $global_var"  12&nbsp;}    13&nbsp;  14&nbsp;func  15&nbsp;  16&nbsp;# Now, to see if local variable "loc_var" exists outside function.  17&nbsp;  18&nbsp;echo  19&nbsp;echo "\"loc_var\" outside function = $loc_var"  20&nbsp;                                      # $loc_var outside function =   21&nbsp;                                      # No, $loc_var not visible globally.  22&nbsp;echo "\"global_var\" outside function = $global_var"  23&nbsp;                                      # $global_var outside function = 999  24&nbsp;                                      # $global_var is visible globally.  25&nbsp;echo				        26&nbsp;  27&nbsp;exit 0  28&nbsp;#  In contrast to C, a Bash variable declared inside a function  29&nbsp;#+ 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&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;func ()   4&nbsp;{   5&nbsp;global_var=37    #  Visible only within the function block   6&nbsp;                 #+ before the function has been called.    7&nbsp;}                #  END OF FUNCTION   8&nbsp;   9&nbsp;echo "global_var = $global_var"  # global_var =  10&nbsp;                                 #  Function "func" has not yet been called,  11&nbsp;                                 #+ so $global_var is not visible here.  12&nbsp;  13&nbsp;func  14&nbsp;echo "global_var = $global_var"  # global_var = 37  15&nbsp;                                 # 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&nbsp;#!/bin/bash   2&nbsp;# recursion-demo.sh   3&nbsp;# Demonstration of recursion.   4&nbsp;   5&nbsp;RECURSIONS=9   # How many times to recurse.   6&nbsp;r_count=0      # Must be global. Why?   7&nbsp;   8&nbsp;recurse ()   9&nbsp;{  10&nbsp;  var="$1"  11&nbsp;  12&nbsp;  while [ "$var" -ge 0 ]  13&nbsp;  do  14&nbsp;    echo "Recursion count = "$r_count"  +-+  \$var = "$var""  15&nbsp;    (( var-- )); (( r_count++ ))  16&nbsp;    recurse "$var"  #  Function calls itself (recurses)  17&nbsp;  done              #+ until what condition is met?  18&nbsp;}  19&nbsp;  20&nbsp;recurse $RECURSIONS  21&nbsp;  22&nbsp;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&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;#               factorial   4&nbsp;#               ---------   5&nbsp;   6&nbsp;   7&nbsp;# Does bash permit recursion?   8&nbsp;# Well, yes, but...   9&nbsp;# It's so slow that you gotta have rocks in your head to try it.  10&nbsp;  11&nbsp;  12&nbsp;MAX_ARG=5  13&nbsp;E_WRONG_ARGS=65  14&nbsp;E_RANGE_ERR=66  15&nbsp;  16&nbsp;  17&nbsp;if [ -z "$1" ]  18&nbsp;then  19&nbsp;  echo "Usage: `basename $0` number"  20&nbsp;  exit $E_WRONG_ARGS  21&nbsp;fi  22&nbsp;  23&nbsp;if [ "$1" -gt $MAX_ARG ]  24&nbsp;then  25&nbsp;  echo "Out of range (5 is maximum)."  26&nbsp;  #  Let's get real now.  27&nbsp;  #  If you want greater range than this,  28&nbsp;  #+ rewrite it in a Real Programming Language.  29&nbsp;  exit $E_RANGE_ERR  30&nbsp;fi    31&nbsp;  32&nbsp;fact ()  33&nbsp;{  34&nbsp;  local number=$1  35&nbsp;  #  Variable "number" must be declared as local,  36&nbsp;  #+ otherwise this doesn't work.  37&nbsp;  if [ "$number" -eq 0 ]  38&nbsp;  then  39&nbsp;    factorial=1    # Factorial of 0 = 1.  40&nbsp;  else  41&nbsp;    let "decrnum = number - 1"  42&nbsp;    fact $decrnum  # Recursive function call (the function calls itself).  43&nbsp;    let "factorial = $number * $?"  44&nbsp;  fi  45&nbsp;  46&nbsp;  return $factorial  47&nbsp;}  48&nbsp;  49&nbsp;fact $1  50&nbsp;echo "Factorial of $1 is $?."  51&nbsp;  52&nbsp;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&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;#  Warning: Running this script could possibly lock up your system!   4&nbsp;#  If you're lucky, it will segfault before using up all available memory.   5&nbsp;   6&nbsp;recursive_function ()		      7&nbsp;{   8&nbsp;echo "$1"     # Makes the function do something, and hastens the segfault.   9&nbsp;(( $1 &#60; $2 )) &#38;&#38; recursive_function $(( $1 + 1 )) $2;  10&nbsp;#  As long as 1st parameter is less than 2nd,  11&nbsp;#+ increment 1st and recurse.  12&nbsp;}  13&nbsp;  14&nbsp;recursive_function 1 50000  # Recurse 50,000 levels!  15&nbsp;#  Most likely segfaults (depending on stack size, set by ulimit -m).  16&nbsp;  17&nbsp;#  Recursion this deep might cause even a C program to segfault,  18&nbsp;#+ by using up all the memory allotted to the stack.  19&nbsp;  20&nbsp;  21&nbsp;echo "This will probably not print."  22&nbsp;exit 0  # This script will not exit normally.  23&nbsp;  24&nbsp;#  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 + -