书上的脚本比较多 记录比较有用的脚本

更好的方式检查命令行参数是否为数字

40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format).
41 #
42 # case "$1" in
43 # "" ) lines=50;;
44 # *[!0-9]*) echo "Usage: `basename $0` lines-to-cleanup";
45 # exit $E_WRONGARGS;;
46 # * ) lines=$1;;
47 # esac


更好的方式检查命令行参数数量是否正确

1 E_WRONG_ARGS=85
2 script_parameters="-a -h -m -z"
3 # -a = all, -h = help, etc.
4
5 if [ $# -ne $Number_of_expected_args ]
6 then
7 echo "Usage: `basename $0` $script_parameters"
8 # `basename $0` is the script's filename.
9 exit $E_WRONG_ARGS
10 fi


更好的方式检查是否在正确的目录

63 # cd /var/log || {
64 # echo "Cannot change to necessary directory." >&2
65 # exit $E_XCD;
66 # }


备份源目录的文件并且在目标目录解压

(cd /source/directory && tar cf - . ) | (cd /dest/directory && tar xpvf -)
一个更加有效的脚本是
cd source/directory
# tar cf - . | (cd ../dest/directory; tar xpvf -)
或
cp -a /source/directory/* /dest/directory
# cp -a /source/directory/* /source/directory/.[^.]* /dest/directory 
#这个复制源目录的隐藏文件


备份最近24小时内改变的文件

#!/bin/bash

BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}
# 如果在命令行中没有指定参数,就是用如下的格式
# it will default to "backup-MM-DD-YYYY.tar.gz."

tar cvf - `find . -mtime -1 -type f -print` > $archive.tar
gzip $archive.tar
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."


如果文件太多或者文件名有空白字符,上面的脚本可能出错

更好的备份方案   tar -r 追加到归档文件

# -------------------------------------------------------------------
# find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
或
# find . -mtime -1 -type f -exec tar rvf "$archive.tar" '{}' \;
exit 0


获取命令行参数的最后一个参数

args=$# # Number of args passed.
lastarg=${!args}
# Note: This is an *indirect reference* to $args ...
# Or: lastarg=${!#}


${file#*/} :拿掉第一条 / 及其左边的字符串:dir1/dir2/dir3/my.file.txt
${file##*/} :拿掉最后一条 / 及其左边的字符串:my.file.txt
${file#*.} :拿掉第一个 . 及其左边的字符串:file.txt
${file##*.} :拿掉最后一个 . 及其左边的字符串:txt
${file%/*} :拿掉最后条 / 及其右边的字符串:/dir1/dir2/dir3
${file%%/*} :拿掉第一条 / 及其右边的字符串:(空值)
${file%.*} :拿掉最后一个 . 及其右边的字符串:/dir1/dir2/dir3/my.file
${file%%.*} :拿掉第一个 . 及其右边的字符串:/dir1/dir2/dir3/my