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

📄 here-docs.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 2 页
字号:
><P><B>Example 17-8. A script that generates another script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# generate-script.sh   3&nbsp;# Based on an idea by Albert Reiner.   4&nbsp;   5&nbsp;OUTFILE=generated.sh         # Name of the file to generate.   6&nbsp;   7&nbsp;   8&nbsp;# -----------------------------------------------------------   9&nbsp;# 'Here document containing the body of the generated script.  10&nbsp;(  11&nbsp;cat &#60;&#60;'EOF'  12&nbsp;#!/bin/bash  13&nbsp;  14&nbsp;echo "This is a generated shell script."  15&nbsp;#  Note that since we are inside a subshell,  16&nbsp;#+ we can't access variables in the "outside" script.  17&nbsp;  18&nbsp;echo "Generated file will be named: $OUTFILE"  19&nbsp;#  Above line will not work as normally expected  20&nbsp;#+ because parameter expansion has been disabled.  21&nbsp;#  Instead, the result is literal output.  22&nbsp;  23&nbsp;a=7  24&nbsp;b=3  25&nbsp;  26&nbsp;let "c = $a * $b"  27&nbsp;echo "c = $c"  28&nbsp;  29&nbsp;exit 0  30&nbsp;EOF  31&nbsp;) &#62; $OUTFILE  32&nbsp;# -----------------------------------------------------------  33&nbsp;  34&nbsp;#  Quoting the 'limit string' prevents variable expansion  35&nbsp;#+ within the body of the above 'here document.'  36&nbsp;#  This permits outputting literal strings in the output file.  37&nbsp;  38&nbsp;if [ -f "$OUTFILE" ]  39&nbsp;then  40&nbsp;  chmod 755 $OUTFILE  41&nbsp;  # Make the generated file executable.  42&nbsp;else  43&nbsp;  echo "Problem in creating file: \"$OUTFILE\""  44&nbsp;fi  45&nbsp;  46&nbsp;#  This method can also be used for generating  47&nbsp;#+ C programs, Perl programs, Python programs, Makefiles,  48&nbsp;#+ and the like.  49&nbsp;  50&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>        It is possible to set a variable from the output of a here document.	<TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;variable=$(cat &#60;&#60;SETVAR   2&nbsp;This variable   3&nbsp;runs over multiple lines.   4&nbsp;SETVAR)   5&nbsp;   6&nbsp;echo "$variable"</PRE></TD></TR></TABLE>      </P><P>A here document can supply input to a function in the same        script.</P><DIVCLASS="EXAMPLE"><HR><ANAME="HF"></A><P><B>Example 17-9. Here documents and functions</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# here-function.sh   3&nbsp;   4&nbsp;GetPersonalData ()   5&nbsp;{   6&nbsp;  read firstname   7&nbsp;  read lastname   8&nbsp;  read address   9&nbsp;  read city   10&nbsp;  read state   11&nbsp;  read zipcode  12&nbsp;} # This certainly looks like an interactive function, but...  13&nbsp;  14&nbsp;  15&nbsp;# Supply input to the above function.  16&nbsp;GetPersonalData &#60;&#60;RECORD001  17&nbsp;Bozo  18&nbsp;Bozeman  19&nbsp;2726 Nondescript Dr.  20&nbsp;Baltimore  21&nbsp;MD  22&nbsp;21226  23&nbsp;RECORD001  24&nbsp;  25&nbsp;  26&nbsp;echo  27&nbsp;echo "$firstname $lastname"  28&nbsp;echo "$address"  29&nbsp;echo "$city, $state $zipcode"  30&nbsp;echo  31&nbsp;  32&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="ANONHEREDOC0"></A></P><P>It is possible to use <SPANCLASS="TOKEN">:</SPAN> as a dummy command        accepting output from a here document. This, in effect, creates an	<SPANCLASS="QUOTE">"anonymous"</SPAN> here document.</P><DIVCLASS="EXAMPLE"><HR><ANAME="ANONHEREDOC"></A><P><B>Example 17-10. <SPANCLASS="QUOTE">"Anonymous"</SPAN> Here Document</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;: &#60;&#60;TESTVARIABLES   4&nbsp;${HOSTNAME?}${USER?}${MAIL?}  # Print error message if one of the variables not set.   5&nbsp;TESTVARIABLES   6&nbsp;   7&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P><ANAME="CBLOCK1"></A></P><DIVCLASS="TIP"><TABLECLASS="TIP"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/tip.png"HSPACE="5"ALT="Tip"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>A variation of the above technique permits <SPANCLASS="QUOTE">"commenting        out"</SPAN> blocks of code.</P></TD></TR></TABLE></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="COMMENTBLOCK"></A><P><B>Example 17-11. Commenting out a block of code</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# commentblock.sh   3&nbsp;   4&nbsp;: &#60;&#60;COMMENTBLOCK   5&nbsp;echo "This line will not echo."   6&nbsp;This is a comment line missing the "#" prefix.   7&nbsp;This is another comment line missing the "#" prefix.   8&nbsp;   9&nbsp;&#38;*@!!++=  10&nbsp;The above line will cause no error message,  11&nbsp;because the Bash interpreter will ignore it.  12&nbsp;COMMENTBLOCK  13&nbsp;  14&nbsp;echo "Exit value of above \"COMMENTBLOCK\" is $?."   # 0  15&nbsp;# No error shown.  16&nbsp;  17&nbsp;  18&nbsp;#  The above technique also comes in useful for commenting out  19&nbsp;#+ a block of working code for debugging purposes.  20&nbsp;#  This saves having to put a "#" at the beginning of each line,  21&nbsp;#+ then having to go back and delete each "#" later.  22&nbsp;  23&nbsp;: &#60;&#60;DEBUGXXX  24&nbsp;for file in *  25&nbsp;do  26&nbsp; cat "$file"  27&nbsp;done  28&nbsp;DEBUGXXX  29&nbsp;  30&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="TIP"><TABLECLASS="TIP"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/tip.png"HSPACE="5"ALT="Tip"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>Yet another twist of this nifty trick makes        <SPANCLASS="QUOTE">"self-documenting"</SPAN> scripts possible.</P></TD></TR></TABLE></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="SELFDOCUMENT"></A><P><B>Example 17-12. A self-documenting script</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# self-document.sh: self-documenting script   3&nbsp;# Modification of "colm.sh".   4&nbsp;   5&nbsp;DOC_REQUEST=70   6&nbsp;   7&nbsp;if [ "$1" = "-h"  -o "$1" = "--help" ]     # Request help.   8&nbsp;then   9&nbsp;  echo; echo "Usage: $0 [directory-name]"; echo  10&nbsp;  sed --silent -e '/DOCUMENTATIONXX$/,/^DOCUMENTATIONXX$/p' "$0" |  11&nbsp;  sed -e '/DOCUMENTATIONXX$/d'; exit $DOC_REQUEST; fi  12&nbsp;  13&nbsp;  14&nbsp;: &#60;&#60;DOCUMENTATIONXX  15&nbsp;List the statistics of a specified directory in tabular format.  16&nbsp;---------------------------------------------------------------  17&nbsp;The command line parameter gives the directory to be listed.  18&nbsp;If no directory specified or directory specified cannot be read,  19&nbsp;then list the current working directory.  20&nbsp;  21&nbsp;DOCUMENTATIONXX  22&nbsp;  23&nbsp;if [ -z "$1" -o ! -r "$1" ]  24&nbsp;then  25&nbsp;  directory=.  26&nbsp;else  27&nbsp;  directory="$1"  28&nbsp;fi    29&nbsp;  30&nbsp;echo "Listing of "$directory":"; echo  31&nbsp;(printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \  32&nbsp;; ls -l "$directory" | sed 1d) | column -t  33&nbsp;  34&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>Using a <AHREF="here-docs.html#CATSCRIPTREF">cat script</A> is an        alternate way of accomplishing this.</P><P>      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;DOC_REQUEST=70   2&nbsp;   3&nbsp;if [ "$1" = "-h"  -o "$1" = "--help" ]     # Request help.   4&nbsp;then                                       # Use a "cat script" . . .   5&nbsp;  cat &#60;&#60;DOCUMENTATIONXX   6&nbsp;List the statistics of a specified directory in tabular format.   7&nbsp;---------------------------------------------------------------   8&nbsp;The command line parameter gives the directory to be listed.   9&nbsp;If no directory specified or directory specified cannot be read,  10&nbsp;then list the current working directory.  11&nbsp;  12&nbsp;DOCUMENTATIONXX  13&nbsp;exit $DOC_REQUEST  14&nbsp;fi</PRE></TD></TR></TABLE>      </P><P>See also <AHREF="contributed-scripts.html#ISSPAMMER2">Example A-27</A> for one more excellent example        of a self-documenting script.</P><DIVCLASS="NOTE"><TABLECLASS="NOTE"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/note.png"HSPACE="5"ALT="Note"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>Here documents create temporary files, but these	    files are deleted after opening and are not accessible to	    any other process.</P><P>	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="SCREEN"> <TTCLASS="PROMPT">bash$ </TT><TTCLASS="USERINPUT"><B>bash -c 'lsof -a -p $$ -d0' &#60;&#60; EOF</B></TT> <TTCLASS="PROMPT">&#62; </TT><TTCLASS="USERINPUT"><B>EOF</B></TT> <TTCLASS="COMPUTEROUTPUT">lsof    1213 bozo    0r   REG    3,5    0 30386 /tmp/t1213-0-sh (deleted)</TT> 	      </PRE></TD></TR></TABLE>	  </P></TD></TR></TABLE></DIV><DIVCLASS="CAUTION"><TABLECLASS="CAUTION"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/caution.png"HSPACE="5"ALT="Caution"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>Some utilities will not work inside a	  <ICLASS="EMPHASIS">here document</I>.</P></TD></TR></TABLE></DIV><P><ANAME="INDENTEDLS"></A></P><DIVCLASS="WARNING"><TABLECLASS="WARNING"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/warning.png"HSPACE="5"ALT="Warning"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>The closing <ICLASS="EMPHASIS">limit string</I>,	  on the final line of a here document, must start in the	  <ICLASS="EMPHASIS">first</I> character position. There can	  be <ICLASS="EMPHASIS">no leading whitespace</I>. Trailing	  whitespace after the limit string likewise causes unexpected	  behavior. The whitespace prevents the limit string from being	  recognized.</P><P>	 <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;echo "----------------------------------------------------------------------"   4&nbsp;   5&nbsp;cat &#60;&#60;LimitString   6&nbsp;echo "This is line 1 of the message inside the here document."   7&nbsp;echo "This is line 2 of the message inside the here document."   8&nbsp;echo "This is the final line of the message inside the here document."   9&nbsp;     LimitString  10&nbsp;#^^^^Indented limit string. Error! This script will not behave as expected.  11&nbsp;  12&nbsp;echo "----------------------------------------------------------------------"  13&nbsp;  14&nbsp;#  These comments are outside the 'here document',  15&nbsp;#+ and should not echo.  16&nbsp;  17&nbsp;echo "Outside the here document."  18&nbsp;  19&nbsp;exit 0  20&nbsp;  21&nbsp;echo "This line had better not echo."  # Follows an 'exit' command.</PRE></TD></TR></TABLE>	 </P></TD></TR></TABLE></DIV><P>For those tasks too complex for a <SPANCLASS="QUOTE">"here	  document"</SPAN>, consider using the <BCLASS="COMMAND">expect</B>	  scripting language, which is specifically tailored for feeding	  input into interactive programs.</P><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="AEN13393">17.1. Here Strings</A></H1><P><ANAME="HERESTRINGSREF"></A></P><P>A <ICLASS="EMPHASIS">here string</I> can be considered as	   a stripped-down form of <ICLASS="EMPHASIS">here document</I>. It	   consists of nothing more than <BCLASS="COMMAND">COMMAND	   &#60;&#60;&#60;$WORD</B>, where <TTCLASS="VARNAME">$WORD</TT>	   is expanded and fed to the <TTCLASS="FILENAME">stdin</TT> of	   <TTCLASS="VARNAME">COMMAND</TT>.</P><DIVCLASS="EXAMPLE"><HR><ANAME="PREPENDEX"></A><P><B>Example 17-13. Prepending a line to a file</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# prepend.sh: Add text at beginning of file.   3&nbsp;#   4&nbsp;#  Example contributed by Kenny Stauffer,   5&nbsp;#+ and slightly modified by document author.   6&nbsp;   7&nbsp;   8&nbsp;E_NOSUCHFILE=65   9&nbsp;  10&nbsp;read -p "File: " file   # -p arg to 'read' displays prompt.  11&nbsp;if [ ! -e "$file" ]  12&nbsp;then   # Bail out if no such file.  13&nbsp;  echo "File $file not found."  14&nbsp;  exit $E_NOSUCHFILE  15&nbsp;fi  16&nbsp;  17&nbsp;read -p "Title: " title  18&nbsp;cat - $file &#60;&#60;&#60;$title &#62; $file.new  19&nbsp;  20&nbsp;echo "Modified file is $file.new"  21&nbsp;  22&nbsp;exit 0  23&nbsp;  24&nbsp;# from 'man bash':  25&nbsp;# Here Strings  26&nbsp;# 	A variant of here documents, the format is:  27&nbsp;#   28&nbsp;# 		&#60;&#60;&#60;word  29&nbsp;#   30&nbsp;# 	The word is expanded and supplied to the command on its standard input.</PRE></TD></TR></TABLE><HR></DIV><P>Exercise: Find other uses for <ICLASS="EMPHASIS">here            strings</I>.</P></DIV></DIV><DIVCLASS="NAVFOOTER"><HRALIGN="LEFT"WIDTH="100%"><TABLEWIDTH="100%"BORDER="0"CELLPADDING="0"CELLSPACING="0"><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top"><AHREF="redirapps.html">Prev</A></TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="index.html">Home</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top"><AHREF="recess-time.html">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Applications</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="part3.html">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Recess Time</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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