📄 scrstyle.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 PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}" 2 # It made perfect sense when you wrote it last year, 3 #+ but now it's a complete mystery. 4 # (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 #!/bin/bash 2 3 #************************************************# 4 # xyz.sh # 5 # written by Bozo Bozeman # 6 # July 05, 2001 # 7 # # 8 # Clean up project files. # 9 #************************************************# 10 11 E_BADDIR=65 # No such directory. 12 projectdir=/home/bozo/projects # Directory to clean up. 13 14 # --------------------------------------------------------- # 15 # cleanup_pfiles () # 16 # Removes all files in designated directory. # 17 # Parameter: $target_directory # 18 # Returns: 0 on success, $E_BADDIR if something went wrong. # 19 # --------------------------------------------------------- # 20 cleanup_pfiles () 21 { 22 if [ ! -d "$1" ] # Test if target directory exists. 23 then 24 echo "$1 is not a directory." 25 return $E_BADDIR 26 fi 27 28 rm -f "$1"/* 29 return 0 # Success. 30 } 31 32 cleanup_pfiles $projectdir 33 34 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 if [ -f /var/log/messages ] 2 then 3 ... 4 fi 5 # A year later, you decide to change the script to check /var/log/syslog. 6 # It is now necessary to manually change the script, instance by instance, 7 # and hope nothing breaks. 8 9 # A better way: 10 LOGFILE=/var/log/messages # Only line that needs to be changed. 11 if [ -f "$LOGFILE" ] 12 then 13 ... 14 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 fl=`ls -al $dirname` # Cryptic. 2 file_listing=`ls -al $dirname` # Better. 3 4 5 MAXVAL=10 # All caps used for a script constant. 6 while [ "$index" -le "$MAXVAL" ] 7 ... 8 9 10 E_NOTFOUND=75 # Uppercase for an errorcode, 11 # +and name begins with "E_". 12 if [ ! -e "$filename" ] 13 then 14 echo "File $filename not found." 15 exit $E_NOTFOUND 16 fi 17 18 19 MAIL_DIRECTORY=/var/spool/mail/bozo # Uppercase for an environmental variable. 20 export MAIL_DIRECTORY 21 22 23 GetAnswer () # Mixed case works well for a function. 24 { 25 prompt=$1 26 echo -n $prompt 27 read answer 28 return $answer 29 } 30 31 GetAnswer "What is your favorite number? " 32 favorite_number=$? 33 echo $favorite_number 34 35 36 _uservariable=23 # Permissible, but not recommended. 37 # It's better for user-defined variables not to start with an underscore. 38 # 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 E_WRONG_ARGS=65 2 ... 3 ... 4 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 -a All: Return all information (including hidden file info). 2 -b Brief: Short version, usually for other scripts. 3 -c Copy, concatenate, etc. 4 -d Daily: Use information from the whole day, and not merely 5 information for a specific instance/user. 6 -e Extended/Elaborate: (often does not include hidden file info). 7 -h Help: Verbose usage w/descs, aux info, discussion, help. 8 See also -V. 9 -l Log output of script. 10 -m Manual: Launch man-page for base command. 11 -n Numbers: Numerical data only. 12 -r Recursive: All files in a directory (and/or all sub-dirs). 13 -s Setup & File Maintenance: Config files for this script. 14 -u Usage: List of invocation flags for the script. 15 -v Verbose: Human readable output, more or less formatted. 16 -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 COMMAND 2 if [ $? -eq 0 ] 3 ... 4 # Redundant and non-intuitive. 5 6 if COMMAND 7 ... 8 # 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%"> </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%"> </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 + -