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

📄 internal.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 5 页
字号:
NAME="EX43"></A><P><B>Example 11-11. Showing the effect of <BCLASS="COMMAND">eval</B></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;y=`eval ls -l`  #  Similar to y=`ls -l`   4&nbsp;echo $y         #+ but linefeeds removed because "echoed" variable is unquoted.   5&nbsp;echo   6&nbsp;echo "$y"       #  Linefeeds preserved when variable is quoted.   7&nbsp;   8&nbsp;echo; echo   9&nbsp;  10&nbsp;y=`eval df`     #  Similar to y=`df`  11&nbsp;echo $y         #+ but linefeeds removed.  12&nbsp;  13&nbsp;#  When LF's not preserved, it may make it easier to parse output,  14&nbsp;#+ using utilities such as "awk".  15&nbsp;  16&nbsp;echo  17&nbsp;echo "==========================================================="  18&nbsp;echo  19&nbsp;  20&nbsp;# Now, showing how to "expand" a variable using "eval" . . .  21&nbsp;  22&nbsp;for i in 1 2 3 4 5; do  23&nbsp;  eval value=$i  24&nbsp;  #  value=$i has same effect. The "eval" is not necessary here.  25&nbsp;  #  A variable lacking a meta-meaning evaluates to itself --  26&nbsp;  #+ it can't expand to anything other than its literal self.  27&nbsp;  echo $value  28&nbsp;done  29&nbsp;  30&nbsp;echo  31&nbsp;echo "---"  32&nbsp;echo  33&nbsp;  34&nbsp;for i in ls df; do  35&nbsp;  value=eval $i  36&nbsp;  #  value=$i has an entirely different effect here.  37&nbsp;  #  The "eval" evaluates the commands "ls" and "df" . . .  38&nbsp;  #  The terms "ls" and "df" have a meta-meaning,  39&nbsp;  #+ since they are interpreted as commands,  40&nbsp;  #+ rather than just character strings.  41&nbsp;  echo $value  42&nbsp;done  43&nbsp;  44&nbsp;  45&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="EX44"></A><P><B>Example 11-12. Forcing a log-off</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# Killing ppp to force a log-off.   3&nbsp;   4&nbsp;# Script should be run as root user.   5&nbsp;   6&nbsp;killppp="eval kill -9 `ps ax | awk '/ppp/ { print $1 }'`"   7&nbsp;#                     -------- process ID of ppp -------     8&nbsp;   9&nbsp;$killppp                  # This variable is now a command.  10&nbsp;  11&nbsp;  12&nbsp;# The following operations must be done as root user.  13&nbsp;  14&nbsp;chmod 666 /dev/ttyS3      # Restore read+write permissions, or else what?  15&nbsp;#  Since doing a SIGKILL on ppp changed the permissions on the serial port,  16&nbsp;#+ we restore permissions to previous state.  17&nbsp;  18&nbsp;rm /var/lock/LCK..ttyS3   # Remove the serial port lock file. Why?  19&nbsp;  20&nbsp;exit 0  21&nbsp;  22&nbsp;# Exercises:  23&nbsp;# ---------  24&nbsp;# 1) Have script check whether root user is invoking it.  25&nbsp;# 2) Do a check on whether the process to be killed  26&nbsp;#+   is actually running before attempting to kill it.     27&nbsp;# 3) Write an alternate version of this script based on 'fuser':  28&nbsp;#+      if [ fuser -s /dev/modem ]; then . . .</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="ROT14"></A><P><B>Example 11-13. A version of <SPANCLASS="QUOTE">"rot13"</SPAN></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# A version of "rot13" using 'eval'.   3&nbsp;# Compare to "rot13.sh" example.   4&nbsp;   5&nbsp;setvar_rot_13()              # "rot13" scrambling   6&nbsp;{   7&nbsp;  local varname=$1 varvalue=$2   8&nbsp;  eval $varname='$(echo "$varvalue" | tr a-z n-za-m)'   9&nbsp;}  10&nbsp;  11&nbsp;  12&nbsp;setvar_rot_13 var "foobar"   # Run "foobar" through rot13.  13&nbsp;echo $var                    # sbbone  14&nbsp;  15&nbsp;setvar_rot_13 var "$var"     # Run "sbbone" through rot13.  16&nbsp;                             # Back to original variable.  17&nbsp;echo $var                    # foobar  18&nbsp;  19&nbsp;# This example by Stephane Chazelas.  20&nbsp;# Modified by document author.  21&nbsp;  22&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Rory Winston contributed the following instance of how	      useful <BCLASS="COMMAND">eval</B> can be.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EVALEX"></A><P><B>Example 11-14. Using <BCLASS="COMMAND">eval</B> to force variable	        substitution in a Perl script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;In the Perl script "test.pl":   2&nbsp;        ...		   3&nbsp;        my $WEBROOT = &#60;WEBROOT_PATH&#62;;   4&nbsp;        ...   5&nbsp;   6&nbsp;To force variable substitution try:   7&nbsp;        $export WEBROOT_PATH=/usr/local/webroot   8&nbsp;        $sed 's/&#60;WEBROOT_PATH&#62;/$WEBROOT_PATH/' &#60; test.pl &#62; out   9&nbsp;  10&nbsp;But this just gives:  11&nbsp;        my $WEBROOT = $WEBROOT_PATH;  12&nbsp;  13&nbsp;However:  14&nbsp;        $export WEBROOT_PATH=/usr/local/webroot  15&nbsp;        $eval sed 's%\&#60;WEBROOT_PATH\&#62;%$WEBROOT_PATH%' &#60; test.pl &#62; out  16&nbsp;#        ====  17&nbsp;  18&nbsp;That works fine, and gives the expected substitution:  19&nbsp;        my $WEBROOT = /usr/local/webroot;  20&nbsp;  21&nbsp;  22&nbsp;### Correction applied to original example by Paulo Marcel Coelho Aragao.</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>The <BCLASS="COMMAND">eval</B> command can be	      risky, and normally should be avoided when there	      exists a reasonable alternative. An <TTCLASS="USERINPUT"><B>eval	      $COMMANDS</B></TT> executes the contents of	      <TTCLASS="REPLACEABLE"><I>COMMANDS</I></TT>, which may	      contain such unpleasant surprises as <BCLASS="COMMAND">rm -rf	      *</B>. Running an <BCLASS="COMMAND">eval</B> on	      unfamiliar code written by persons unknown is living	      dangerously.</P></TD></TR></TABLE></DIV></DD><DT><ANAME="SETREF"></A><BCLASS="COMMAND">set</B></DT><DD><P>The <BCLASS="COMMAND">set</B> command changes	      the value of internal script variables. One use for	      this is to toggle <AHREF="options.html#OPTIONSREF">option	      flags</A> which help determine the behavior of the	      script. Another application for it is to reset the <AHREF="variables2.html#POSPARAMREF">positional parameters</A> that	      a script sees as the result of a command (<TTCLASS="USERINPUT"><B>set	      `command`</B></TT>). The script can then parse the	      fields of the command output.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX34"></A><P><B>Example 11-15. Using <BCLASS="COMMAND">set</B> with positional	        parameters</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# script "set-test"   4&nbsp;   5&nbsp;# Invoke this script with three command line parameters,   6&nbsp;# for example, "./set-test one two three".   7&nbsp;   8&nbsp;echo   9&nbsp;echo "Positional parameters before  set \`uname -a\` :"  10&nbsp;echo "Command-line argument #1 = $1"  11&nbsp;echo "Command-line argument #2 = $2"  12&nbsp;echo "Command-line argument #3 = $3"  13&nbsp;  14&nbsp;  15&nbsp;set `uname -a` # Sets the positional parameters to the output  16&nbsp;               # of the command `uname -a`  17&nbsp;  18&nbsp;echo $_        # unknown  19&nbsp;# Flags set in script.  20&nbsp;  21&nbsp;echo "Positional parameters after  set \`uname -a\` :"  22&nbsp;# $1, $2, $3, etc. reinitialized to result of `uname -a`  23&nbsp;echo "Field #1 of 'uname -a' = $1"  24&nbsp;echo "Field #2 of 'uname -a' = $2"  25&nbsp;echo "Field #3 of 'uname -a' = $3"  26&nbsp;echo ---  27&nbsp;echo $_        # ---  28&nbsp;echo  29&nbsp;  30&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Invoking <BCLASS="COMMAND">set</B> without any options or	      arguments simply lists all the <AHREF="othertypesv.html#ENVREF">environmental</A> and other variables	      that have been initialized.	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>set</B></TT> <TTCLASS="COMPUTEROUTPUT">AUTHORCOPY=/home/bozo/posts BASH=/bin/bash BASH_VERSION=$'2.05.8(1)-release' ... XAUTHORITY=/home/bozo/.Xauthority _=/etc/bashrc variable22=abc variable23=xzy</TT> 	      </PRE></TD></TR></TABLE>            </P><P>Using <BCLASS="COMMAND">set</B> with the <TTCLASS="OPTION">--</TT>	      option explicitly assigns the contents of a variable to	      the positional parameters. When no variable follows the	      <TTCLASS="OPTION">--</TT>, it <ICLASS="EMPHASIS">unsets</I>	      the positional parameters.</P><DIVCLASS="EXAMPLE"><HR><ANAME="SETPOS"></A><P><B>Example 11-16. Reassigning the positional parameters</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;variable="one two three four five"   4&nbsp;   5&nbsp;set -- $variable   6&nbsp;# Sets positional parameters to the contents of "$variable".   7&nbsp;   8&nbsp;first_param=$1   9&nbsp;second_param=$2  10&nbsp;shift; shift        # Shift past first two positional params.  11&nbsp;remaining_params="$*"  12&nbsp;  13&nbsp;echo  14&nbsp;echo "first parameter = $first_param"             # one  15&nbsp;echo "second parameter = $second_param"           # two  16&nbsp;echo "remaining parameters = $remaining_params"   # three four five  17&nbsp;  18&nbsp;echo; echo  19&nbsp;  20&nbsp;# Again.  21&nbsp;set -- $variable  22&nbsp;first_param=$1  23&nbsp;second_param=$2  24&nbsp;echo "first parameter = $first_param"             # one  25&nbsp;echo "second parameter = $second_param"           # two  26&nbsp;  27&nbsp;# ======================================================  28&nbsp;  29&nbsp;set --  30&nbsp;# Unsets positional parameters if no variable specified.  31&nbsp;  32&nbsp;first_param=$1  33&nbsp;second_param=$2  34&nbsp;echo "first parameter = $first_param"             # (null value)  35&nbsp;echo "second parameter = $second_param"           # (null value)  36&nbsp;  37&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>See also <AHREF="loops.html#EX22A">Example 10-2</A> and <AHREF="extmisc.html#EX33A">Example 12-51</A>.</P></DD><DT><ANAME="UNSETREF"></A><BCLASS="COMMAND">unset</B></DT><DD><P>The <BCLASS="COMMAND">unset</B> command deletes a	      shell variable, effectively setting it to	      <ICLASS="EMPHASIS">null</I>. Note that this command does	      not affect positional parameters.</P><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>unset PATH</B></TT>  <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>echo $PATH</B></TT> <TTCLASS="COMPUTEROUTPUT">&#13;</TT> <TTCLASS="PROMPT">bash$ </TT></PRE></TD></TR></TABLE>	    </P><DIVCLASS="EXAMPLE"><HR><ANAME="UNS"></A><P><B>Example 11-17. <SPANCLASS="QUOTE">"Unsetting"</SPAN> a variable</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# unset.sh: Unsetting a variable.   3&nbsp;   4&nbsp;variable=hello                       # Initialized.   5&nbsp;echo "variable = $variable"   6&nbsp;   7&nbsp;unset variable                       # Unset.   8&nbsp;                                     # Same effect as:  variable=   9&nbsp;echo "(unset) variable = $variable"  # $variable is null.  10&nbsp;  11&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV></DD><DT><ANAME="EXPORTREF"></A><BCLASS="COMMAND">export</B></DT><DD><P>The <BCLASS="COMMAND">export</B> command makes	      available variables to all child processes of the	      running script or shell. <ICLASS="EMPHASIS">Unfortunately, there	      is no way to</I> export <ICLASS="EMPHASIS">variables back	      to the parent process, to the process that called or	      invoked the script or shell.</I> One important	      use of the <BCLASS="COMMAND">export</B> command is in <AHREF="files.html#FILESREF1">startup files</A>, to initialize	      and make accessible <AHREF="othertypesv.html#ENVREF">environmental	      variables</A> to subsequent user processes.</P><DIVCLASS="EXAMPLE"><HR><ANAME="COLTOTALER3"></A><P><B>Example 11-18. Using <BCLASS="COMMAND">export</B> to pass a variable to an	      embedded <AHREF="awk.html#AWKREF">awk</A> script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;#  Yet another version of the "column totaler" script (col-totaler.sh)   4&nbsp;#+ that adds up a specified column (of numbers) in the target file.   5&nbsp;#  This uses the environment to pass a script variable to 'awk' . . .   6&nbsp;#+ and places the awk script in a variable.   7&nbsp;   8&nbsp;   9&nbsp;ARGS=2  10&nbsp;E_WRONGARGS=65  11&nbsp;  12&nbsp;if [ $# -ne "$ARGS" ] # Check for proper no. of command line args.  13&nbsp;then  14&nbsp;   echo "Usage: `basename $0` filename column-number"  15&nbsp;   exit $E_WRONGARGS  16&nbsp;fi  17&nbsp;  18&nbsp;filename=$1  19&nbsp;column_number=$2  20&nbsp;  21&nbsp;#===== Same as original script, up to this point =====#  22&nbsp;  23&nbsp;export column_number  24&nbsp;# Export column number to environment, so it's available for retrieval.  25&nbsp;  26&nbsp;  27&nbsp;# -----------------------------------------------  28&nbsp;awkscript='{ total += $ENVIRON["column_number"] }  29&nbsp;END { print total }'  30&nbsp;# Yes, a variable can hold an awk script.  31&nbsp;# -----------------------------------------------  32&nbsp;  33&nbsp;# Now, run the awk script.

⌨️ 快捷键说明

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