AdvancedBash-ShellGuide(Version10)学习笔记三

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

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

成都网站建设、网站建设介绍好的网站是理念、设计和技术的结合。创新互联拥有的网站设计理念、多方位的设计风格、经验丰富的设计团队。提供PC端+手机端网站建设,用营销思维进行网站设计、采用先进技术开源代码、注重用户体验与SEO基础,将技术与创意整合到网站之中,以契合客户的方式做到创意性的视觉化效果。

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




网站标题:AdvancedBash-ShellGuide(Version10)学习笔记三
网页URL:http://csdahua.cn/article/pcjodg.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流