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

📄 functions.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Functions</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.57"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Advanced Topics"HREF="part4.html"><LINKREL="PREVIOUS"TITLE="Process Substitution"HREF="process-sub.html"><LINKREL="NEXT"TITLE="Local Variables"HREF="localvar.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="CHAPTER"BGCOLOR="#FFFFFF"TEXT="#000000"LINK="#AA0000"VLINK="#AA0055"ALINK="#AA0000"STYLE="font-family: sans-serif;"><DIVCLASS="NAVHEADER"><TABLEWIDTH="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="process-sub.html">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom"></TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="localvar.html">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="CHAPTER"><H1><ANAME="FUNCTIONS">Chapter 23. Functions</A></H1><P><ANAME="FUNCTIONREF"></A></P><P>Like <SPANCLASS="QUOTE">"real"</SPAN> programming languages,	Bash has functions, though in a somewhat limited implementation.	A function is a subroutine, a <AHREF="special-chars.html#CODEBLOCKREF">code	block</A> that implements a set of operations, a <SPANCLASS="QUOTE">"black	box"</SPAN> that performs a specified task.  Wherever there is	repetitive code, when a task repeats with only slight variations,	then consider using a function.</P><P><P><BCLASS="COMMAND">function</B>   <TTCLASS="REPLACEABLE"><I>function_name</I></TT>   { <BR>  <TTCLASS="REPLACEABLE"><I>command</I></TT>... <BR>  } <BR></P>	or 	<P> <TTCLASS="REPLACEABLE"><I>function_name</I></TT>   ()   { <BR>  <TTCLASS="REPLACEABLE"><I>command</I></TT>... <BR>  } <BR></P>      </P><P>This second form will cheer the hearts of C programmers        (and is more portable).</P><P>As in C, the function's opening bracket may optionally appear        on the second line.</P><P><P> <TTCLASS="REPLACEABLE"><I>function_name</I></TT>   () <BR>  { <BR>  <TTCLASS="REPLACEABLE"><I>command</I></TT>... <BR>  } <BR></P>      </P><P>Functions are called, <ICLASS="FIRSTTERM">triggered</I>, simply by	invoking their names.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX59"></A><P><B>Example 23-1. Simple functions</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;JUST_A_SECOND=1   4&nbsp;   5&nbsp;funky ()   6&nbsp;{ # This is about as simple as functions get.   7&nbsp;  echo "This is a funky function."   8&nbsp;  echo "Now exiting funky function."   9&nbsp;} # Function declaration must precede call.  10&nbsp;  11&nbsp;  12&nbsp;fun ()  13&nbsp;{ # A somewhat more complex function.  14&nbsp;  i=0  15&nbsp;  REPEATS=30  16&nbsp;  17&nbsp;  echo  18&nbsp;  echo "And now the fun really begins."  19&nbsp;  echo  20&nbsp;  21&nbsp;  sleep $JUST_A_SECOND    # Hey, wait a second!  22&nbsp;  while [ $i -lt $REPEATS ]  23&nbsp;  do  24&nbsp;    echo "----------FUNCTIONS----------&#62;"  25&nbsp;    echo "&#60;------------ARE-------------"  26&nbsp;    echo "&#60;------------FUN------------&#62;"  27&nbsp;    echo  28&nbsp;    let "i+=1"  29&nbsp;  done  30&nbsp;}  31&nbsp;  32&nbsp;  # Now, call the functions.  33&nbsp;  34&nbsp;funky  35&nbsp;fun  36&nbsp;  37&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>The function definition must precede the first call to	it. There is no method of <SPANCLASS="QUOTE">"declaring"</SPAN> the function,	as, for example, in C.	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;f1   2&nbsp;# Will give an error message, since function "f1" not yet defined.   3&nbsp;   4&nbsp;declare -f f1      # This doesn't help either.   5&nbsp;f1                 # Still an error message.   6&nbsp;   7&nbsp;# However...   8&nbsp;   9&nbsp;	    10&nbsp;f1 ()  11&nbsp;{  12&nbsp;  echo "Calling function \"f2\" from within function \"f1\"."  13&nbsp;  f2  14&nbsp;}  15&nbsp;  16&nbsp;f2 ()  17&nbsp;{  18&nbsp;  echo "Function \"f2\"."  19&nbsp;}  20&nbsp;  21&nbsp;f1  #  Function "f2" is not actually called until this point,  22&nbsp;    #+ although it is referenced before its definition.  23&nbsp;    #  This is permissible.  24&nbsp;      25&nbsp;    # Thanks, S.C.</PRE></TD></TR></TABLE>      </P><P>It is even possible to nest a function within another function,        although this is not very useful.	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;f1 ()   2&nbsp;{   3&nbsp;   4&nbsp;  f2 () # nested   5&nbsp;  {   6&nbsp;    echo "Function \"f2\", inside \"f1\"."   7&nbsp;  }   8&nbsp;   9&nbsp;}    10&nbsp;  11&nbsp;f2  #  Gives an error message.  12&nbsp;    #  Even a preceding "declare -f f2" wouldn't help.  13&nbsp;  14&nbsp;echo      15&nbsp;  16&nbsp;f1  #  Does nothing, since calling "f1" does not automatically call "f2".  17&nbsp;f2  #  Now, it's all right to call "f2",  18&nbsp;    #+ since its definition has been made visible by calling "f1".  19&nbsp;  20&nbsp;    # Thanks, S.C.</PRE></TD></TR></TABLE>      </P><P>Function declarations can appear in unlikely places, even where a        command would otherwise go.          <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;ls -l | foo() { echo "foo"; }  # Permissible, but useless.   2&nbsp;   3&nbsp;   4&nbsp;   5&nbsp;if [ "$USER" = bozo ]   6&nbsp;then   7&nbsp;  bozo_greet ()   # Function definition embedded in an if/then construct.   8&nbsp;  {   9&nbsp;    echo "Hello, Bozo."  10&nbsp;  }  11&nbsp;fi    12&nbsp;  13&nbsp;bozo_greet        # Works only for Bozo, and other users get an error.  14&nbsp;  15&nbsp;  16&nbsp;  17&nbsp;# Something like this might be useful in some contexts.  18&nbsp;NO_EXIT=1   # Will enable function definition below.  19&nbsp;  20&nbsp;[[ $NO_EXIT -eq 1 ]] &#38;&#38; exit() { true; }     # Function definition in an "and-list".  21&nbsp;# If $NO_EXIT is 1, declares "exit ()".  22&nbsp;# This disables the "exit" builtin by aliasing it to "true".  23&nbsp;  24&nbsp;exit  # Invokes "exit ()" function, not "exit" builtin.  25&nbsp;  26&nbsp;# Thanks, S.C.</PRE></TD></TR></TABLE>      </P><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="COMPLEXFUNCT">23.1. Complex Functions and Function Complexities</A></H1><P>Functions may process arguments passed to them and return	an <AHREF="exit-status.html#EXITSTATUSREF">exit status</A> to the script	for further processing.</P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;function_name $arg1 $arg2</PRE></TD></TR></TABLE><P>The function refers to the passed arguments by position (as if they were	<AHREF="variables2.html#POSPARAMREF">positional parameters</A>),	that is, <TTCLASS="VARNAME">$1</TT>, <TTCLASS="VARNAME">$2</TT>, and	so forth.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX60"></A><P><B>Example 23-2. Function Taking Parameters</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# Functions and parameters   3&nbsp;   4&nbsp;DEFAULT=default                             # Default param value.   5&nbsp;   6&nbsp;func2 () {   7&nbsp;   if [ -z "$1" ]                           # Is parameter #1 zero length?   8&nbsp;   then   9&nbsp;     echo "-Parameter #1 is zero length.-"  # Or no parameter passed.  10&nbsp;   else  11&nbsp;     echo "-Param #1 is \"$1\".-"  12&nbsp;   fi  13&nbsp;  14&nbsp;   variable=${1-$DEFAULT}                   #  What does  15&nbsp;   echo "variable = $variable"              #+ parameter substitution show?  16&nbsp;                                            #  ---------------------------  17&nbsp;                                            #  It distinguishes between  18&nbsp;                                            #+ no param and a null param.  19&nbsp;  20&nbsp;   if [ "$2" ]  21&nbsp;   then  22&nbsp;     echo "-Parameter #2 is \"$2\".-"  23&nbsp;   fi  24&nbsp;  25&nbsp;   return 0  26&nbsp;}  27&nbsp;  28&nbsp;echo  29&nbsp;     30&nbsp;echo "Nothing passed."     31&nbsp;func2                          # Called with no params  32&nbsp;echo  33&nbsp;  34&nbsp;  35&nbsp;echo "Zero-length parameter passed."  36&nbsp;func2 ""                       # Called with zero-length param  37&nbsp;echo  38&nbsp;  39&nbsp;echo "Null parameter passed."  40&nbsp;func2 "$uninitialized_param"   # Called with uninitialized param  41&nbsp;echo  42&nbsp;  43&nbsp;echo "One parameter passed."     44&nbsp;func2 first           # Called with one param  45&nbsp;echo  46&nbsp;  47&nbsp;echo "Two parameters passed."     48&nbsp;func2 first second    # Called with two params  49&nbsp;echo  50&nbsp;  51&nbsp;echo "\"\" \"second\" passed."  52&nbsp;func2 "" second       # Called with zero-length first parameter  53&nbsp;echo                  # and ASCII string as a second one.  54&nbsp;  55&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="IMPORTANT"><TABLECLASS="IMPORTANT"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/important.png"HSPACE="5"ALT="Important"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>The <AHREF="othertypesv.html#SHIFTREF">shift</A>        command works on arguments passed to functions (see <AHREF="assortedtips.html#MULTIPLICATION">Example 33-15</A>).</P></TD></TR></TABLE></DIV><P>But, what about command-line arguments passed to the script?         Does a function see them? Well, let's clear up the confusion.</P><DIVCLASS="EXAMPLE"><HR><ANAME="FUNCCMDLINEARG"></A><P><B>Example 23-3. Functions and command-line args passed to the script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# func-cmdlinearg.sh   3&nbsp;#  Call this script with a command-line argument,   4&nbsp;#+ something like $0 arg1.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -