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

📄 scrstyle.html

📁 Shall高级编程
💻 HTML
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Scripting With Style</TITLE><METANAME="GENERATOR"CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+"><LINKREL="HOME"TITLE="Advanced Bash-Scripting Guide"HREF="index.html"><LINKREL="UP"TITLE="Advanced Topics"HREF="part5.html"><LINKREL="PREVIOUS"TITLE="Gotchas"HREF="gotchas.html"><LINKREL="NEXT"TITLE="Miscellany"HREF="miscellany.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"><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="gotchas.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom"></TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="miscellany.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="CHAPTER"><H1><ANAME="SCRSTYLE"></A>Chapter 32. Scripting With Style</H1><P>Get into the habit of writing shell scripts in a structured and	systematic manner. Even <SPANCLASS="QUOTE">"on-the-fly"</SPAN> and	<SPANCLASS="QUOTE">"written on the back of an envelope"</SPAN> scripts will	benefit if you take a few minutes to plan and organize your	thoughts before sitting down and coding.</P><P>Herewith are a few stylistic guidelines. This is not        intended as an <SPANCLASS="emphasis"><ICLASS="EMPHASIS">Official Shell Scripting	Stylesheet</I></SPAN>.</P><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="UNOFFICIALST"></A>32.1. Unofficial Shell Scripting Stylesheet</H1><UL><LI><P>Comment your code. This makes it easier for others to	    understand (and appreciate), and easier for you to maintain.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"   2&nbsp;#  It made perfect sense when you wrote it last year,   3&nbsp;#+ but now it's a complete mystery.   4&nbsp;#  (From Antek Sawicki's "pw.sh" script.)</PRE></TD></TR></TABLE>	  </P><P>Add descriptive headers to your scripts and functions.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;#************************************************#   4&nbsp;#                   xyz.sh                       #   5&nbsp;#           written by Bozo Bozeman              #   6&nbsp;#                July 05, 2001                   #   7&nbsp;#                                                #   8&nbsp;#           Clean up project files.              #   9&nbsp;#************************************************#  10&nbsp;  11&nbsp;E_BADDIR=65                       # No such directory.  12&nbsp;projectdir=/home/bozo/projects    # Directory to clean up.  13&nbsp;  14&nbsp;# --------------------------------------------------------- #  15&nbsp;# cleanup_pfiles ()                                         #  16&nbsp;# Removes all files in designated directory.                #  17&nbsp;# Parameter: $target_directory                              #  18&nbsp;# Returns: 0 on success, $E_BADDIR if something went wrong. #  19&nbsp;# --------------------------------------------------------- #  20&nbsp;cleanup_pfiles ()  21&nbsp;{  22&nbsp;  if [ ! -d "$1" ]  # Test if target directory exists.  23&nbsp;  then  24&nbsp;    echo "$1 is not a directory."  25&nbsp;    return $E_BADDIR  26&nbsp;  fi  27&nbsp;  28&nbsp;  rm -f "$1"/*  29&nbsp;  return 0   # Success.  30&nbsp;}    31&nbsp;  32&nbsp;cleanup_pfiles $projectdir  33&nbsp;  34&nbsp;exit 0</PRE></TD></TR></TABLE>	    Be sure to put the <ICLASS="FIRSTTERM">#!/bin/bash</I> at the	    beginning of the first line of the script, preceding any	    comment headers.</P></LI><LI><P>Avoid using <SPANCLASS="QUOTE">"magic numbers,"</SPAN>	     <ANAME="AEN18302"HREF="#FTN.AEN18302">[1]</A>	    that is, <SPANCLASS="QUOTE">"hard-wired"</SPAN> literal constants. Use	    meaningful variable names instead. This makes the script	    easier to understand and permits making changes and updates	    without breaking the application.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;if [ -f /var/log/messages ]   2&nbsp;then   3&nbsp;  ...   4&nbsp;fi   5&nbsp;# A year later, you decide to change the script to check /var/log/syslog.   6&nbsp;# It is now necessary to manually change the script, instance by instance,   7&nbsp;# and hope nothing breaks.   8&nbsp;   9&nbsp;# A better way:  10&nbsp;LOGFILE=/var/log/messages  # Only line that needs to be changed.  11&nbsp;if [ -f "$LOGFILE" ]  12&nbsp;then  13&nbsp;  ...  14&nbsp;fi</PRE></TD></TR></TABLE>          </P></LI><LI><P>Choose descriptive names for variables and functions.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;fl=`ls -al $dirname`                 # Cryptic.   2&nbsp;file_listing=`ls -al $dirname`       # Better.   3&nbsp;   4&nbsp;   5&nbsp;MAXVAL=10   # All caps used for a script constant.   6&nbsp;while [ "$index" -le "$MAXVAL" ]   7&nbsp;...   8&nbsp;   9&nbsp;  10&nbsp;E_NOTFOUND=75                        #  Uppercase for an errorcode,  11&nbsp;                                     # +and name begins with "E_".  12&nbsp;if [ ! -e "$filename" ]  13&nbsp;then  14&nbsp;  echo "File $filename not found."  15&nbsp;  exit $E_NOTFOUND  16&nbsp;fi    17&nbsp;  18&nbsp;  19&nbsp;MAIL_DIRECTORY=/var/spool/mail/bozo  # Uppercase for an environmental variable.  20&nbsp;export MAIL_DIRECTORY  21&nbsp;  22&nbsp;  23&nbsp;GetAnswer ()                         # Mixed case works well for a function.  24&nbsp;{  25&nbsp;  prompt=$1  26&nbsp;  echo -n $prompt  27&nbsp;  read answer  28&nbsp;  return $answer  29&nbsp;}    30&nbsp;  31&nbsp;GetAnswer "What is your favorite number? "  32&nbsp;favorite_number=$?  33&nbsp;echo $favorite_number  34&nbsp;  35&nbsp;  36&nbsp;_uservariable=23                     # Permissible, but not recommended.  37&nbsp;# It's better for user-defined variables not to start with an underscore.  38&nbsp;# Leave that for system variables.</PRE></TD></TR></TABLE>          </P></LI><LI><P>Use <AHREF="exit-status.html#EXITCOMMANDREF">exit codes</A>	    in a systematic and meaningful way.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;E_WRONG_ARGS=65   2&nbsp;...   3&nbsp;...   4&nbsp;exit $E_WRONG_ARGS</PRE></TD></TR></TABLE>            See also <AHREF="exitcodes.html">Appendix D</A>.</P><P><SPANCLASS="emphasis"><ICLASS="EMPHASIS">Ender</I></SPAN> suggests using the exit codes	    in <TTCLASS="FILENAME">/usr/include/sysexits.h</TT> in shell	    scripts, though these are primarily intended for C and C++	    programming.</P></LI><LI><P>Use standardized parameter flags for script invocation.	     <SPANCLASS="emphasis"><ICLASS="EMPHASIS">Ender</I></SPAN> proposes the following set	     of flags.</P><P>             <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;-a      All: Return all information (including hidden file info).   2&nbsp;-b      Brief: Short version, usually for other scripts.   3&nbsp;-c      Copy, concatenate, etc.   4&nbsp;-d      Daily: Use information from the whole day, and not merely   5&nbsp;        information for a specific instance/user.   6&nbsp;-e      Extended/Elaborate: (often does not include hidden file info).   7&nbsp;-h      Help: Verbose usage w/descs, aux info, discussion, help.   8&nbsp;        See also -V.   9&nbsp;-l      Log output of script.  10&nbsp;-m      Manual: Launch man-page for base command.  11&nbsp;-n      Numbers: Numerical data only.  12&nbsp;-r      Recursive: All files in a directory (and/or all sub-dirs).  13&nbsp;-s      Setup &#38; File Maintenance: Config files for this script.  14&nbsp;-u      Usage: List of invocation flags for the script.  15&nbsp;-v      Verbose: Human readable output, more or less formatted.  16&nbsp;-V      Version / License / Copy(right|left) / Contribs (email too).</PRE></TD></TR></TABLE>           </P><P>See also <AHREF="command-line-options.html#STANDARD-OPTIONS">Section F.1</A>.</P></LI><LI><P>Break complex scripts into simpler modules. Use functions	    where appropriate. See <AHREF="bash2.html#EX79">Example 34-4</A>.</P></LI><LI><P>Don't use a complex construct where a simpler one will do.	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;COMMAND   2&nbsp;if [ $? -eq 0 ]   3&nbsp;...   4&nbsp;# Redundant and non-intuitive.   5&nbsp;   6&nbsp;if COMMAND   7&nbsp;...   8&nbsp;# More concise (if perhaps not quite as legible).</PRE></TD></TR></TABLE>          </P></LI></UL><TABLEBORDER="0"WIDTH="100%"CELLSPACING="0"CELLPADDING="0"CLASS="EPIGRAPH"><TR><TDWIDTH="45%">&nbsp;</TD><TDWIDTH="45%"ALIGN="LEFT"VALIGN="TOP"><I><P><I>... reading the UNIX source code to the Bourne shell (/bin/sh). I        was shocked at how much simple algorithms could be made cryptic, and	therefore useless, by a poor choice of code style. I asked myself,	<SPANCLASS="QUOTE">"Could someone be proud of this code?"</SPAN></I></P></I></TD></TR><TR><TDWIDTH="45%">&nbsp;</TD><TDWIDTH="45%"ALIGN="RIGHT"VALIGN="TOP"><I><SPANCLASS="ATTRIBUTION">Landon Noll</SPAN></I></TD></TR></TABLE></DIV></DIV><H3CLASS="FOOTNOTES">Notes</H3><TABLEBORDER="0"CLASS="FOOTNOTES"WIDTH="100%"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="5%"><ANAME="FTN.AEN18302"HREF="scrstyle.html#AEN18302">[1]</A></TD><TDALIGN="LEFT"VALIGN="TOP"WIDTH="95%"><P>In this context, <SPANCLASS="QUOTE">"magic	       numbers"</SPAN> have an entirely different meaning than	       the <AHREF="sha-bang.html#MAGNUMREF">magic numbers</A> used	       to designate file types.</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="gotchas.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="miscellany.html"ACCESSKEY="N">Next</A></TD></TR><TR><TDWIDTH="33%"ALIGN="left"VALIGN="top">Gotchas</TD><TDWIDTH="34%"ALIGN="center"VALIGN="top"><AHREF="part5.html"ACCESSKEY="U">Up</A></TD><TDWIDTH="33%"ALIGN="right"VALIGN="top">Miscellany</TD></TR></TABLE></DIV></BODY></HTML>

⌨️ 快捷键说明

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