Example 2-2. _cleanup_: An improved clean-up script
#!/bin/bash# Proper header for a Bash script.# Cleanup, version 2# Run as root, of course.# Insert code here to print error message and exit if not root.LOG_DIR=/var/log# Variables are better than hard-coded values.cd $LOG_DIRcat/dev/null>messagescat/dev/null>wtmpecho"Logs cleaned up."exit# The right and proper method of "exiting" from a script.# A bare "exit" (no parameter) returns the exit status#+ of the preceding command.
現在這個開始看起來像個真正的 script 了,只是我們可以再更進一步 ...
Example 2-3. _cleanup_: 上述 script 的加強版。
#!/bin/bash# Cleanup, version 3# Warning:# -------# This script uses quite a number of features that will be explained#+ later on.# By the time you've finished the first half of the book,#+ there should be nothing mysterious about it.LOG_DIR=/var/logROOT_UID=0# Only users with $UID 0 have root privileges.LINES=50# Default number of lines saved.E_XCD=86# Can't change directory?E_NOTROOT=87# Non-root exit error.# Run as root, of course.if [ "$UID"-ne"$ROOT_UID" ]thenecho"Must be root to run this script."exit $E_NOTROOTfiif [ -n"$1" ]# Test whether command-line argument is present (non-empty).then lines=$1else lines=$LINES # Default, if not specified on command-line.fi# Stephane Chazelas suggests the following,#+ as a better way of checking command-line arguments,#+ but this is still a bit advanced for this stage of the tutorial.## E_WRONGARGS=85 # Non-numerical argument (bad argument format).## case "$1" in# "" ) lines=50;;# *[!0-9]*) echo "Usage: `basename $0` lines-to-cleanup";# exit $E_WRONGARGS;;# * ) lines=$1;;# esac##* Skip ahead to "Loops" chapter to decipher all this.cd $LOG_DIRif [ `pwd`!="$LOG_DIR" ] # or if [ "$PWD" != "$LOG_DIR" ]# Not in /var/log?thenecho"Can't change to $LOG_DIR."exit $E_XCDfi# Doublecheck if in right directory before messing with log file.# Far more efficient is:## cd /var/log || {# echo "Cannot change to necessary directory." >&2# exit $E_XCD;# }tail-n $lines messages>mesg.temp# Save last section of message log file.mvmesg.tempmessages# Rename it as system log file.# cat /dev/null > messages#* No longer needed, as the above method is safer.cat/dev/null>wtmp# ': > wtmp' and '> wtmp' have the same effect.echo"Log files cleaned up."# Note that there are other log files in /var/log not affected#+ by this script.exit0# A zero return value from the script upon exit indicates success#+ to the shell.
#!/bin/bashecho"Part 1 of script."a=1#!/bin/bash# This does *not* launch a new script.echo"Part 2 of script."echo $a # Value of $a stays at 1.
這裡可以接受一些可愛的小把戲。
#!/bin/rm# Self-deleting script.# Nothing much seems to happen when you run this... except that the file disappears.WHATEVER=85echo"This line will never print (betcha!)."exit $WHATEVER # Doesn't matter. The script will not exit here.# Try an echo $? after script termination.# You'll get a 0, not a 85.