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

📄 assortedtips.html

📁 Shall高级编程
💻 HTML
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><TITLE>Assorted Tips</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="Optimizations"HREF="optimizations.html"><LINKREL="NEXT"TITLE="Security Issues"HREF="securityissues.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="optimizations.html"ACCESSKEY="P">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 33. Miscellany</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="securityissues.html"ACCESSKEY="N">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="ASSORTEDTIPS"></A>33.8. Assorted Tips</H1><DIVCLASS="SECT2"><H2CLASS="SECT2"><ANAME="AEN18867"></A>33.8.1. Ideas for more powerful scripts</H2><UL><LI><P><ANAME="PSEUDOCODEREF"></A></P><P>You have a problem that you want to solve by writing a Bash	     script. Unfortunately, you don't know quite where to start.	     One method is to plunge right in and code those parts	     of the script that come easily, and write the hard parts as	     <ICLASS="FIRSTTERM">pseudo-code</I>.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;ARGCOUNT=1                     # Need name as argument.   4&nbsp;E_WRONGARGS=65   5&nbsp;   6&nbsp;if [ number-of-arguments is-not-equal-to "$ARGCOUNT" ]   7&nbsp;#    ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^   8&nbsp;#  Can't figure out how to code this . . .   9&nbsp;#+ . . . so write it in pseudo-code.  10&nbsp;  11&nbsp;then  12&nbsp;  echo "Usage: name-of-script name"  13&nbsp;  #            ^^^^^^^^^^^^^^     More pseudo-code.  14&nbsp;  exit $E_WRONGARGS  15&nbsp;fi   16&nbsp;  17&nbsp;. . .  18&nbsp;  19&nbsp;exit 0  20&nbsp;  21&nbsp;  22&nbsp;# Later on, substitute working code for the pseudo-code.  23&nbsp;  24&nbsp;# Line 6 becomes:  25&nbsp;if [ $# -ne "$ARGCOUNT" ]  26&nbsp;  27&nbsp;# Line 12 becomes:  28&nbsp;  echo "Usage: `basename $0` name"</PRE></TD></TR></TABLE></P><P>For an example of using pseudo-code, see the <AHREF="writingscripts.html#NEWTONSQRT">Square Root</A> exercise.</P></LI><LI><P><ANAME="TRACKINGSCR"></A></P><P>To keep a record of which user scripts have run	    during a particular session or over a number of sessions,	    add the following lines to each script you want to keep track	    of. This will keep a continuing file record of the script	    names and invocation times. </P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# Append (&#62;&#62;) following to end of each script tracked.   2&nbsp;   3&nbsp;whoami&#62;&#62; $SAVE_FILE    # User invoking the script.   4&nbsp;echo $0&#62;&#62; $SAVE_FILE   # Script name.   5&nbsp;date&#62;&#62; $SAVE_FILE      # Date and time.   6&nbsp;echo&#62;&#62; $SAVE_FILE      # Blank line as separator.   7&nbsp;   8&nbsp;#  Of course, SAVE_FILE defined and exported as environmental variable in ~/.bashrc   9&nbsp;#+ (something like ~/.scripts-run)</PRE></TD></TR></TABLE>          </P></LI><LI><P><ANAME="PREPENDREF"></A></P><P>The <SPANCLASS="TOKEN">&#62;&#62;</SPAN> operator	    <ICLASS="FIRSTTERM">appends</I> lines to a file.	    What if you wish to <ICLASS="FIRSTTERM">prepend</I> a	    line to an existing file, that is, to paste it in at the	    beginning?</P><P>	  <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;file=data.txt   2&nbsp;title="***This is the title line of data text file***"   3&nbsp;   4&nbsp;echo $title | cat - $file &#62;$file.new   5&nbsp;# "cat -" concatenates stdout to $file.   6&nbsp;#  End result is   7&nbsp;#+ to write a new file with $title appended at *beginning*.</PRE></TD></TR></TABLE>	  </P><P>This is a simplified variant of the <AHREF="here-docs.html#PREPENDEX">Example 18-13</A> script given earlier.	And, of course,	    <AHREF="sedawk.html#SEDREF">sed</A> can also do this.</P></LI><LI><P><ANAME="SCRIPTASEMB"></A></P><P>A shell script may act as an embedded command inside	    another shell script, a <ICLASS="FIRSTTERM">Tcl</I> or	    <ICLASS="FIRSTTERM">wish</I> script, or even a <AHREF="filearchiv.html#MAKEFILEREF">Makefile</A>. It can be invoked	    as an external shell command in a C program using the	    <TTCLASS="REPLACEABLE"><I>system()</I></TT> call, i.e.,	   <TTCLASS="REPLACEABLE"><I>system("script_name");</I></TT>.</P></LI><LI><P><ANAME="SETVAREMB"></A></P><P>Setting a variable to the contents of an embedded	    <ICLASS="FIRSTTERM">sed</I> or <ICLASS="FIRSTTERM">awk</I>	    script increases the readability of the surrounding <AHREF="wrapper.html#SHWRAPPER">shell wrapper</A>. See <AHREF="contributed-scripts.html#MAILFORMAT">Example A-1</A> and <AHREF="internal.html#COLTOTALER3">Example 14-20</A>.</P></LI><LI><P><ANAME="LIBROUTINES"></A></P><P>Put together files containing your favorite and most useful	    definitions and functions.	As necessary,	    <SPANCLASS="QUOTE">"include"</SPAN> one or more of these	    <SPANCLASS="QUOTE">"library files"</SPAN> in scripts with either the	    <AHREF="special-chars.html#DOTREF">dot</A> (<BCLASS="COMMAND">.</B>)	    or <AHREF="internal.html#SOURCEREF">source</A> command.</P><P>              <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;# SCRIPT LIBRARY   2&nbsp;# ------ -------   3&nbsp;   4&nbsp;# Note:   5&nbsp;# No "#!" here.   6&nbsp;# No "live code" either.   7&nbsp;   8&nbsp;   9&nbsp;# Useful variable definitions  10&nbsp;  11&nbsp;ROOT_UID=0             # Root has $UID 0.  12&nbsp;E_NOTROOT=101          # Not root user error.   13&nbsp;MAXRETVAL=255          # Maximum (positive) return value of a function.  14&nbsp;SUCCESS=0  15&nbsp;FAILURE=-1  16&nbsp;  17&nbsp;  18&nbsp;  19&nbsp;# Functions  20&nbsp;  21&nbsp;Usage ()               # "Usage:" message.  22&nbsp;{  23&nbsp;  if [ -z "$1" ]       # No arg passed.  24&nbsp;  then  25&nbsp;    msg=filename  26&nbsp;  else  27&nbsp;    msg=$@  28&nbsp;  fi  29&nbsp;  30&nbsp;  echo "Usage: `basename $0` "$msg""  31&nbsp;}    32&nbsp;  33&nbsp;  34&nbsp;Check_if_root ()       # Check if root running script.  35&nbsp;{                      # From "ex39.sh" example.  36&nbsp;  if [ "$UID" -ne "$ROOT_UID" ]  37&nbsp;  then  38&nbsp;    echo "Must be root to run this script."  39&nbsp;    exit $E_NOTROOT  40&nbsp;  fi  41&nbsp;}    42&nbsp;  43&nbsp;  44&nbsp;CreateTempfileName ()  # Creates a "unique" temp filename.  45&nbsp;{                      # From "ex51.sh" example.  46&nbsp;  prefix=temp  47&nbsp;  suffix=`eval date +%s`  48&nbsp;  Tempfilename=$prefix.$suffix  49&nbsp;}  50&nbsp;  51&nbsp;  52&nbsp;isalpha2 ()            # Tests whether *entire string* is alphabetic.  53&nbsp;{                      # From "isalpha.sh" example.  54&nbsp;  [ $# -eq 1 ] || return $FAILURE  55&nbsp;  56&nbsp;  case $1 in  57&nbsp;  *[!a-zA-Z]*|"") return $FAILURE;;  58&nbsp;  *) return $SUCCESS;;  59&nbsp;  esac                 # Thanks, S.C.  60&nbsp;}  61&nbsp;  62&nbsp;  63&nbsp;abs ()                           # Absolute value.  64&nbsp;{                                # Caution: Max return value = 255.  65&nbsp;  E_ARGERR=-999999  66&nbsp;  67&nbsp;  if [ -z "$1" ]                 # Need arg passed.  68&nbsp;  then  69&nbsp;    return $E_ARGERR             # Obvious error value returned.  70&nbsp;  fi  71&nbsp;  72&nbsp;  if [ "$1" -ge 0 ]              # If non-negative,  73&nbsp;  then                           #  74&nbsp;    absval=$1                    # stays as-is.  75&nbsp;  else                           # Otherwise,  76&nbsp;    let "absval = (( 0 - $1 ))"  # change sign.  77&nbsp;  fi    78&nbsp;  79&nbsp;  return $absval  80&nbsp;}  81&nbsp;  82&nbsp;  83&nbsp;tolower ()             #  Converts string(s) passed as argument(s)  84&nbsp;{                      #+ to lowercase.  85&nbsp;  86&nbsp;  if [ -z "$1" ]       #  If no argument(s) passed,  87&nbsp;  then                 #+ send error message  88&nbsp;    echo "(null)"      #+ (C-style void-pointer error message)  89&nbsp;    return             #+ and return from function.  90&nbsp;  fi    91&nbsp;  92&nbsp;  echo "$@" | tr A-Z a-z  93&nbsp;  # Translate all passed arguments ($@).  94&nbsp;  95&nbsp;  return  96&nbsp;  97&nbsp;# Use command substitution to set a variable to function output.  98&nbsp;# For example:  99&nbsp;#    oldvar="A seT of miXed-caSe LEtTerS" 100&nbsp;#    newvar=`tolower "$oldvar"` 101&nbsp;#    echo "$newvar"    # a set of mixed-case letters 102&nbsp;# 103&nbsp;# Exercise: Rewrite this function to change lowercase passed argument(s) 104&nbsp;#           to uppercase ... toupper()  [easy]. 105&nbsp;}</PRE></TD></TR></TABLE>          </P></LI><LI><P><ANAME="COMMENTH"></A></P><P>Use special-purpose comment headers to increase clarity	    and legibility in scripts.</P><P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;## Caution.   2&nbsp;rm -rf *.zzy   ##  The "-rf" options to "rm" are very dangerous,   3&nbsp;               ##+ especially with wild cards.   4&nbsp;   5&nbsp;#+ Line continuation.   6&nbsp;#  This is line 1   7&nbsp;#+ of a multi-line comment,   8&nbsp;#+ and this is the final line.   9&nbsp;  10&nbsp;#* Note.  11&nbsp;  12&nbsp;#o List item.  13&nbsp;  14&nbsp;#&#62; Another point of view.  15&nbsp;while [ "$var1" != "end" ]    #&#62; while test "$var1" != "end"</PRE></TD></TR></TABLE></P></LI><LI><P><ANAME="COMOUTBL"></A></P><P>A particularly clever use of <AHREF="tests.html#TESTCONSTRUCTS1">if-test</A> constructs	    is for comment blocks.</P><P>    	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;COMMENT_BLOCK=   4&nbsp;#  Try setting the above variable to some value   5&nbsp;#+ for an unpleasant surprise.   6&nbsp;   7&nbsp;if [ $COMMENT_BLOCK ]; then   8&nbsp;   9&nbsp;Comment block --  10&nbsp;=================================  11&nbsp;This is a comment line.  12&nbsp;This is another comment line.  13&nbsp;This is yet another comment line.  14&nbsp;=================================  15&nbsp;  16&nbsp;echo "This will not echo."  17&nbsp;  18&nbsp;Comment blocks are error-free! Whee!  19&nbsp;  20&nbsp;fi  21&nbsp;  22&nbsp;echo "No more comments, please."  23&nbsp;  24&nbsp;exit 0</PRE></TD></TR></TABLE>	  </P><P>Compare this with <AHREF="here-docs.html#CBLOCK1">using  	    here documents to comment out code blocks</A>.</P></LI><LI><P><ANAME="INTPARAM"></A></P><P>Using the <AHREF="variables2.html#XSTATVARREF">$? exit status	    variable</A>, a script may test if a parameter contains	    only digits, so it can be treated as an integer.</P><P>  	    <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="90%"><TR

⌨️ 快捷键说明

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