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

📄 wrapper.html

📁 Shall高级编程
💻 HTML
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Shell Wrappers</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Miscellany"HREF="miscellany.html"><LINKREL="PREVIOUS"TITLE="Operator Precedence"HREF="opprecedence.html"><LINKREL="NEXT"TITLE="Tests and Comparisons: Alternatives"HREF="testsandcomparisons.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="opprecedence.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 33. Miscellany</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="testsandcomparisons.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="WRAPPER"></A>33.3. Shell Wrappers</H1><P><ANAME="SHWRAPPER"></A></P><P>A <SPANCLASS="QUOTE">"wrapper"</SPAN> is a shell script that embeds	a system command or utility, that saves a set of parameters	passed to that command.      <ANAME="AEN18594"HREF="#FTN.AEN18594">[1]</A>		Wrapping a script around a complex command line	simplifies invoking it.  This is expecially useful	with <AHREF="sedawk.html#SEDREF">sed</A> and <AHREF="awk.html#AWKREF">awk</A>.</P><P>A	<BCLASS="COMMAND">	    sed</B> or	<BCLASS="COMMAND">	   	    awk</B> script would normally be invoked	    from the command line by a <TTCLASS="USERINPUT"><B>sed -e	    <TTCLASS="REPLACEABLE"><I>'commands'</I></TT></B></TT>	    or <TTCLASS="USERINPUT"><B>awk	    <TTCLASS="REPLACEABLE"><I>'commands'</I></TT></B></TT>.	Embedding	    such a script in a Bash script permits calling it more simply,	    and makes it <SPANCLASS="QUOTE">"reusable"</SPAN>. This also enables	    combining the functionality of <BCLASS="COMMAND">sed</B>	    and <BCLASS="COMMAND">awk</B>, for example <AHREF="special-chars.html#PIPEREF">piping</A> the output of a set of	    <BCLASS="COMMAND">sed</B> commands to <BCLASS="COMMAND">awk</B>.	    As a saved executable file, you can then repeatedly invoke it	    in its original form or modified, without the inconvenience	    of retyping it on the command line.</P><DIVCLASS="EXAMPLE"><HR><ANAME="EX3"></A><P><B>Example 33-1. <ICLASS="FIRSTTERM">shell wrapper</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# This is a simple script that removes blank lines from a file.   4&nbsp;# No argument checking.   5&nbsp;#   6&nbsp;# You might wish to add something like:   7&nbsp;#   8&nbsp;# E_NOARGS=65   9&nbsp;# if [ -z "$1" ]  10&nbsp;# then  11&nbsp;#  echo "Usage: `basename $0` target-file"  12&nbsp;#  exit $E_NOARGS  13&nbsp;# fi  14&nbsp;  15&nbsp;  16&nbsp;# Same as  17&nbsp;#    sed -e '/^$/d' filename  18&nbsp;# invoked from the command line.  19&nbsp;  20&nbsp;sed -e /^$/d "$1"  21&nbsp;#  The '-e' means an "editing" command follows (optional here).  22&nbsp;#  '^' is the beginning of line, '$' is the end.  23&nbsp;#  This match lines with nothing between the beginning and the end,  24&nbsp;#+ blank lines.  25&nbsp;#  The 'd' is the delete command.  26&nbsp;  27&nbsp;#  Quoting the command-line arg permits  28&nbsp;#+ whitespace and special characters in the filename.  29&nbsp;  30&nbsp;#  Note that this script doesn't actually change the target file.  31&nbsp;#  If you need to do that, redirect its output.  32&nbsp;  33&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="EX4"></A><P><B>Example 33-2.  A slightly more complex <ICLASS="FIRSTTERM">shell	wrapper</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;#  "subst", a script that substitutes one pattern for   4&nbsp;#+ another in a file,   5&nbsp;#+ i.e., "subst Smith Jones letter.txt".   6&nbsp;   7&nbsp;ARGS=3         # Script requires 3 arguments.   8&nbsp;E_BADARGS=65   # Wrong number of arguments passed to script.   9&nbsp;  10&nbsp;if [ $# -ne "$ARGS" ]  11&nbsp;# Test number of arguments to script (always a good idea).  12&nbsp;then  13&nbsp;  echo "Usage: `basename $0` old-pattern new-pattern filename"  14&nbsp;  exit $E_BADARGS  15&nbsp;fi  16&nbsp;  17&nbsp;old_pattern=$1  18&nbsp;new_pattern=$2  19&nbsp;  20&nbsp;if [ -f "$3" ]  21&nbsp;then  22&nbsp;    file_name=$3  23&nbsp;else  24&nbsp;    echo "File \"$3\" does not exist."  25&nbsp;    exit $E_BADARGS  26&nbsp;fi  27&nbsp;  28&nbsp;  29&nbsp;#  Here is where the heavy work gets done.  30&nbsp;  31&nbsp;# -----------------------------------------------  32&nbsp;sed -e "s/$old_pattern/$new_pattern/g" $file_name  33&nbsp;# -----------------------------------------------  34&nbsp;  35&nbsp;#  's' is, of course, the substitute command in sed,  36&nbsp;#+ and /pattern/ invokes address matching.  37&nbsp;#  The "g", or global flag causes substitution for *every*  38&nbsp;#+ occurence of $old_pattern on each line, not just the first.  39&nbsp;#  Read the literature on 'sed' for an in-depth explanation.  40&nbsp;  41&nbsp;exit 0    # Successful invocation of the script returns 0.</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="LOGGINGWRAPPER"></A><P><B>Example 33-3.  A generic <ICLASS="FIRSTTERM">shell wrapper</I> that	writes to a logfile</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;#  Generic shell wrapper that performs an operation   3&nbsp;#+ and logs it.   4&nbsp;   5&nbsp;# Must set the following two variables.   6&nbsp;OPERATION=   7&nbsp;#         Can be a complex chain of commands,   8&nbsp;#+        for example an awk script or a pipe . . .   9&nbsp;LOGFILE=  10&nbsp;#         Command-line arguments, if any, for the operation.  11&nbsp;  12&nbsp;  13&nbsp;OPTIONS="$@"  14&nbsp;  15&nbsp;  16&nbsp;# Log it.  17&nbsp;echo "`date` + `whoami` + $OPERATION "$@"" &#62;&#62; $LOGFILE  18&nbsp;# Now, do it.  19&nbsp;exec $OPERATION "$@"  20&nbsp;  21&nbsp;# It's necessary to do the logging before the operation.  22&nbsp;# Why?</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="PRASC"></A><P><B>Example 33-4.  A <ICLASS="FIRSTTERM">shell wrapper</I> around an awk	script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# pr-ascii.sh: Prints a table of ASCII characters.   3&nbsp;   4&nbsp;START=33   # Range of printable ASCII characters (decimal).   5&nbsp;END=125   6&nbsp;   7&nbsp;echo " Decimal   Hex     Character"   # Header.   8&nbsp;echo " -------   ---     ---------"   9&nbsp;  10&nbsp;for ((i=START; i&#60;=END; i++))  11&nbsp;do  12&nbsp;  echo $i | awk '{printf("  %3d       %2x         %c\n", $1, $1, $1)}'  13&nbsp;# The Bash printf builtin will not work in this context:  14&nbsp;#     printf "%c" "$i"  15&nbsp;done  16&nbsp;  17&nbsp;exit 0  18&nbsp;  19&nbsp;  20&nbsp;#  Decimal   Hex     Character  21&nbsp;#  -------   ---     ---------  22&nbsp;#    33       21         !  23&nbsp;#    34       22         "  24&nbsp;#    35       23         #  25&nbsp;#    36       24         $  26&nbsp;#  27&nbsp;#    . . .  28&nbsp;#  29&nbsp;#   122       7a         z  30&nbsp;#   123       7b         {  31&nbsp;#   124       7c         |  32&nbsp;#   125       7d         }  33&nbsp;  34&nbsp;  35&nbsp;#  Redirect the output of this script to a file  36&nbsp;#+ or pipe it to "more":  sh pr-asc.sh | more</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="COLTOTALER"></A><P><B>Example 33-5.  A <ICLASS="FIRSTTERM">shell wrapper</I> around another	awk script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# Adds up a specified column (of numbers) in the target file.   4&nbsp;   5&nbsp;ARGS=2   6&nbsp;E_WRONGARGS=65   7&nbsp;   8&nbsp;if [ $# -ne "$ARGS" ] # Check for proper no. of command line args.   9&nbsp;then  10&nbsp;   echo "Usage: `basename $0` filename column-number"  11&nbsp;   exit $E_WRONGARGS  12&nbsp;fi  13&nbsp;  14&nbsp;filename=$1  15&nbsp;column_number=$2  16&nbsp;  17&nbsp;#  Passing shell variables to the awk part of the script is a bit tricky.  18&nbsp;#  One method is to strong-quote the Bash-script variable  19&nbsp;#+ within the awk script.  20&nbsp;#     $'$BASH_SCRIPT_VAR'  21&nbsp;#      ^                ^  22&nbsp;#  This is done in the embedded awk script below.  23&nbsp;#  See the awk documentation for more details.  24&nbsp;  25&nbsp;# A multi-line awk script is invoked by:  awk ' ..... '  26&nbsp;  27&nbsp;  28&nbsp;# Begin awk script.  29&nbsp;# -----------------------------  30&nbsp;awk '  31&nbsp;  32&nbsp;{ total += $'"${column_number}"'  33&nbsp;}  34&nbsp;END {  35&nbsp;     print total  36&nbsp;}       37&nbsp;  38&nbsp;' "$filename"  39&nbsp;# -----------------------------  40&nbsp;# End awk script.  41&nbsp;  42&nbsp;  43&nbsp;#   It may not be safe to pass shell variables to an embedded awk script,  44&nbsp;#+  so Stephane Chazelas proposes the following alternative:  45&nbsp;#   ---------------------------------------  46&nbsp;#   awk -v column_number="$column_number" '  47&nbsp;#   { total += $column_number  48&nbsp;#   }  49&nbsp;#   END {  50&nbsp;#       print total  51&nbsp;#   }' "$filename"  52&nbsp;#   ---------------------------------------  53&nbsp;  54&nbsp;  55&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="PERLREF"></A>For those scripts needing a single	do-it-all tool, a Swiss army knife, there is	<ICLASS="FIRSTTERM">Perl</I>. Perl combines the capabilities of	<BCLASS="COMMAND">sed</B> and <BCLASS="COMMAND">awk</B>, and throws in	a large subset of <ICLASS="FIRSTTERM">C</I>, to boot. It is modular	and contains support for everything ranging from object-oriented	programming up to and including the kitchen sink. Short Perl	scripts lend themselves to embedding in shell scripts, and there	may even be some substance to the claim that Perl can totally	replace shell scripting (though the author of this document	remains skeptical).</P><P><ANAME="PERLEMB"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="EX56"></A><P><B>Example 33-6. Perl embedded in a <ICLASS="FIRSTTERM">Bash</I> script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;# Shell commands may precede the Perl script.   4&nbsp;echo "This precedes the embedded Perl script within \"$0\"."   5&nbsp;echo "==============================================================="   6&nbsp;   7&nbsp;perl -e 'print "This is an embedded Perl script.\n";'   8&nbsp;# Like sed, Perl also uses the "-e" option.   9&nbsp;  10&nbsp;echo "==============================================================="  11&nbsp;echo "However, the script may also contain shell and system commands."  12&nbsp;  13&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>It is even possible to combine a Bash script and Perl script        within the same file. Depending on how the script is invoked, either	the Bash part or the Perl part will execute.</P><P><ANAME="BASHANDPERL0"></A></P><DIVCLASS="EXAMPLE"><HR><ANAME="BASHANDPERL"></A><P><B>Example 33-7. Bash and Perl scripts combined</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# bashandperl.sh   3&nbsp;   4&nbsp;echo "Greetings from the Bash part of the script."   5&nbsp;# More Bash commands may follow here.   6&nbsp;   7&nbsp;exit 0   8&nbsp;# End of Bash part of the script.   9&nbsp;  10&nbsp;# =======================================================  11&nbsp;  12&nbsp;#!/usr/bin/perl  13&nbsp;# This part of the script must be invoked with -x option.  14&nbsp;  15&nbsp;print "Greetings from the Perl part of the script.\n";  16&nbsp;# More Perl commands may follow here.  17&nbsp;  18&nbsp;# End of Perl part of the script.</PRE></TD></TR></TABLE><HR></DIV><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>bash bashandperl.sh</B></TT> <TTCLASS="COMPUTEROUTPUT">Greetings from the Bash part of the script.</TT>   <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>perl -x bashandperl.sh</B></TT> <TTCLASS="COMPUTEROUTPUT">Greetings from the Perl part of the script.</TT> 	      </PRE></TD></TR></TABLE>	      </P></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN18594"HREF="wrapper.html#AEN18594">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>Quite a number of Linux utilities are, in fact,	shell wrappers. Some examples are	<TTCLASS="FILENAME">/usr/bin/pdf2ps</TT>,	<TTCLASS="FILENAME">/usr/bin/batch</TT>, and	<TTCLASS="FILENAME">/usr/X11R6/bin/xmkmf</TT>.</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="opprecedence.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="testsandcomparisons.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Operator Precedence</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="miscellany.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Tests and Comparisons: Alternatives</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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