いくつかの要件に応じて/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}に置き換えます。

宿題をよくしてください。

おすすめ記事