千家信息网

Advanced Bash-Shell Guide(Version 10) 学习笔记三

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,书上的脚本比较多 记录比较有用的脚本更好的方式检查命令行参数是否为数字40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format
千家信息网最后更新 2025年12月02日Advanced Bash-Shell Guide(Version 10) 学习笔记三

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

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

40 # E_WRONGARGS=85 # Non-numerical argument (bad argument format).41 #42 # case "$1" in43 # "" ) 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=852 script_parameters="-a -h -m -z"3 # -a = all, -h = help, etc.45 if [ $# -ne $Number_of_expected_args ]6 then7 echo "Usage: `basename $0` $script_parameters"8 # `basename $0` is the script's filename.9 exit $E_WRONG_ARGS10 fi


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

63 # cd /var/log || {64 # echo "Cannot change to necessary directory." >&265 # 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/bashBACKUPFILE=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.targzip $archive.tarecho "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




0