LINUXSHELL小作业


题目

Write a script called homebackup that automates tar so the person executing the script always uses the desired options (cvp) and backup destination directory (/var/backups) to make a backup of his or her home directory. Implement the following features:

Test for the number of arguments. The script should run without arguments. If any arguments are present, exit after printing a usage message.

Determine whether the backups directory has enough free space to hold the backup.

Ask the user whether a full or an incremental backup is wanted. If the user does not have a full backup file yet, print a message that a full backup will be taken. In case of an incremental backup, only do this if the full backup is not older than a week.

Compress the backup using any compression tool. Inform the user that the script is doing this, because it might take some time, during which the user might start worrying if no output appears on the screen.

Print a message informing the user about the size of the compressed backup.

参考实现

#!/bin/bash

ARG_NUM=$#

if [ $ARG_NUM -gt 0 ]
then
        echo "Usage: ./homebackup.sh "
        exit
fi

FREE_SPACE=`df /home/backup | tail -1|awk '{print $4}'`
USER_CHOICE=0

echo "Please input your choice:"
echo "0,full backup"
echo "1,incremental backup"

BACKUP_FILE_NAME="backup"$(date +%Y-%m-%d)".tar.gz"

read USER_CHOICE

case $USER_CHOICE in

0)
        echo "start to backup in full mode"
;;
1)
        echo "start to backup in incremental mode"
        if [ -f "/home/backup/backup.tar.gz" ]
        then
                LAST_BACK_TIME=`stat /home/backup/backup.tar.gz |grep Modify|awk -F. '{print $1}' |awk '{print $2" "$3}'`
                LAST_BACK_TIME=`date -d "$LAST_BACK_TIME" +%s`
                NOW=`date -d "-7 day" +%s`
                if [ $LAST_BACK_TIME -gt $NOW ]
                then
                        echo "You cannot do backup operation"
                        echo "The last backup is on " `date -d @"$LAST_BACK_TIME" +%Y-%m-%d`
                        exit
                fi
        fi
;;
*)
 echo "wrong operation"
        exit
;;
esac

tar -cvf $BACKUP_FILE_NAME *.sh
BACK_UP_SIZE=`ls -la $BACKUP_FILE_NAME|awk '{print $5}' `
if [ $BACK_UP_SIZE  -gt $FREE_SPACE ]
then
	echo "Insufficient space in /home/backup, it need $BACK_UP_SIZE bytes"
	exit
fi

mv $BACKUP_FILE_NAME /home/backup/backup.tar.gz

相关内容