bash 脚本:如何备份/user/home?

bash 脚本:如何备份/user/home?

我目前正在学习脚本,我需要创建一个脚本来使用 .bz2 备份 /user/home。我需要脚本来验证用户是否存在以及是否没有选择要备份的用户。

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

#End result
#user_20151126.tar.bz2

我的脚本:

#!/bin/bash
#Systema Date

DATE=$(date +%F)

#Selecting a username

echo "Select the user to backup: "

read USER

#Selecting the compression method

echo "Enter the compression method:"

echo "Type 1 for gzip"

echo "Type 2 for bzip"

echo "Type 3 for xz"

read METHOD

答案1

类似的事情?

    #!/bin/bash
    if [ $# -ne 2 ]; then # $# - is a number of arguments if its not equal (-ne) to 2 then we print message below and exit script
        echo ${0}" [gzip|bzip2|xz] <user_name>"
        echo -e "\tProgram will create backup of users home directory"
        exit 0 # 0 is a return code of script
    fi
    case $1 in # $1 is first argument of script and case statement runs code depending of its content. for example: if $1 is equal to "gzip" then set method to "z" 
    "gzip" )
        method="z" ;;
    "bzip2" )
        method="j" ;;
    "xz" )
        method="J" ;;
    *)
        # if $1 is none of above then run this
        echo "Wrong method [gzip|bzip2|xz]"
        exit 1 # and exit with return code 1 which means error
        ;;
    esac
    if [ ! -d /home/$2 ]; then # id not(!) existing directory(-d) /home/login ($2 is the second argument of script) then
        echo "User not exists"
        exit 1
    fi
    tar -${method} -cf ${2}_$(date +%F).tar.${1} /home/${2}

它可以做得更好、更短,但这段代码可以让你学到一些东西。有关 tar 的更多信息请参见此处: http://linux.die.net/man/1/tar

相关内容