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

📄 assortedtips.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 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.57"><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"><TABLEWIDTH="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">Prev</A></TD><TDWIDTH="80%"ALIGN="center"VALIGN="bottom">Chapter 33. Miscellany</TD><TDWIDTH="10%"ALIGN="right"VALIGN="bottom"><AHREF="securityissues.html">Next</A></TD></TR></TABLE><HRALIGN="LEFT"WIDTH="100%"></DIV><DIVCLASS="SECT1"><H1CLASS="SECT1"><ANAME="ASSORTEDTIPS">33.7. Assorted Tips</A></H1><UL><LI><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 appends lines to a file.	    What if you wish to <ICLASS="EMPHASIS">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 17-13</A> script given earlier.	And, of course,	    <AHREF="sedawk.html#SEDREF">sed</A> can also do this.</P></LI><LI><P>A shell script may act as an embedded command inside	    another shell script, a <ICLASS="EMPHASIS">Tcl</I> or	    <ICLASS="EMPHASIS">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>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 11-18</A>.</P></LI><LI><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>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 wildcards.   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>A particularly clever use of <AHREF="tests.html#TESTCONSTRUCTS1">if-test</A> constructs	    is commenting out blocks of code.</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>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><TD><PRECLASS="PROGRAMLISTING"

⌨️ 快捷键说明

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