常用 Bash 脚本

2019-10-01 bash language

这里总结一些常见的脚本,例如备份、日志清理等等。

备份脚本

如下是一个备份用的脚本,不过 email 没有调试使用过,暂时记录下。

  • ~/.backuprc 配置文件,列举出那些文件需要备份,使用 # 做注释;
  • 使用 ~/tmp 作为临时目录;

另外,在使用 tar 备份打包+解压时,默认为相对路径,为了使用绝对路径可以在压缩+解压时都使用 -P 参数,这样直接解压即可覆盖原有文件。

#!/bin/bash
# mybackup - Backup selected files & directories and email them as .tar.gz file to
# your email account.
# List of BACKUP files/dirs stored in file ~/.mybackup

FILE=~/.backuprc
NOW=`date +"%d-%m-%Y"`
OUT="`echo $USER.$HOSTNAME`.$NOW.tar.gz"
TAR=/usr/bin/tar

## mail setup
#MTO="nixbackup@somedom.com"
#MSUB="Backup (`echo $USER @ $HOSTNAME`) as on `date`"
#MES=~/tmp/mybackup.txt
#MATT=~/tmp/$OUT

# make sure we put backup in our own tmp and not in /tmp
[ ! -d ~/tmp ] && mkdir ~/tmp || :
if [ -f $FILE ]; then
    IN="`cat $FILE | grep -E -v "^#"`"
else
    echo "File $FILE does not exists"
    exit 3
fi

if [ "$IN" == "" ]; then
    echo "$FILE is empty, please add list of files/directories to backup"
    exit 2
fi

$TAR -zcPf ~/tmp/$OUT $IN >/dev/null

## create message for mail
#echo "Backup successfully done. Please see attached file." > $MES
#echo "" >> $MES
#echo "Backup file: $OUT" >> $MES
#echo "" >> $MES
#
## bug fix, we can't send email with attachment if mutt is not installed
#which mutt > /dev/null
#if [ $? -eq 0 ]; then
#    # now mail backup file with this attachment
#    mutt -s "$MSUB" -a "$MATT" $MTO < $MES
#else
#    echo "Command mutt not found, cannot send an email with attachment"
#fi
#
## clean up
#/bin/rm -f $MATT
#/bin/rm -f $MES

如下,是一个配置文件。

/home/foobar/.vimrc
/home/foobar/.tmux
/home/foobar/.tmux.conf

日志清理脚本

在 Linux 中可以通过 logrotate 对日志进行归档,如下是一个日志清理的脚本。

#!/bin/sh
# log cleaner.

# location of logs lies
LOGPATH=${1:-"/var/log/appname/"}

# days to expire, logs older than ${EXPIRE} days will be removed
EXPIRE=${2:-10}
TMPFILE="/tmp/old_log_files"

echo "log=$LOGPATH, expire=${EXPIRE}"
find ${LOGPATH} -regextype posix-basic -regex "${LOGPATH}[a-z]\+.log.[0-9]\+" \
	-a -mtime "+${EXPIRE}" > ${TMPFILE}
if [ $? -ne 0 ];then
  echo "find older log files failed"
  exit 1
fi

for f in `cat ${TMPFILE}`
do
  /usr/sbin/lsof|grep -q $f
  if [ $? -eq 0 ];then
    echo "$f is still open"
  else
    echo "deleteing file:$f"
    rm -f $f
  fi
done