如何备份/user/home 有一些要求?

如何备份/user/home 有一些要求?

我目前正在学习脚本,我需要创建一个脚本来使用压缩来备份 /user/home .bz2。我的老师希望运行脚本的人选择要备份的用户和压缩方法。我创建了一个非常简单的脚本,但我想对其进行一些调整。

这就是我需要的:

#/bin/bash
#Choose user to backup
#choose compression method.

脚本的最终结果:

user_20151126.tar.bz2

我的脚本:

#!/bin/bash

echo -n Enter a User Name for the back:
read UserName

echo -n Enter the compression method:
read CompressionMethod

tar -jcvf /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethod /home

chmod 777 /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethod

echo "Nightly Backup Successful: $(date)" >> /var/tmp_backup.log

我的结果:

20151126.tar.bz2 

答案1

我建议进行以下更改和错误修复:

#!/bin/bash

#first we test whether we have enough input parameters
if [ "x$1" == "x" ] || [ "x$2" == "x" ]; then
  echo "usage: $0 <user_name> <compression method bz2|gz|Z>"
fi

#test if we have read access to the users home directory
if [ ! -r /home/$1 ]; then
  echo "could not read /home/${1}"
  exit 1
fi

#now we parse the compression method and set the correct tar flag for it
case $2 in
  "bz2")
  flag=j;;
  "gz")
  flag=z;;
  "Z")
  flag=Z;;
  *)
  echo "unsupported compression method valid methods are <bz2|gz|Z>"
  exit 1;;
esac

#we need to enclose variable names not followed by whitespace in {} otherwise the letters following the variable name will be recognized as part of the variable name
tar -${flag}cvf /var/tmp/${1}_$(date +%Y%m%d).tar.$2 /home/${1}/

chmod 777 /var/tmp/${1}_$(date +%Y%m%d).tar.$2

echo "Nightly Backup Successful: $(date)" #>> /var/tmp/backup.log

该脚本的调用方式如下:

backup.sh user bz2

如果您希望以交互方式输入用户名和压缩方法,请使用执行此操作的代码,并将 ${1} 替换为 ${UserName} (将 $1 替换为 $USerName),并将 ${2} 替换为 ${CompressionMethod}

祝你作业顺利。

相关内容