shell脚本将源目录备份到备份目录

时间:2015-11-05 07:47:20

标签: bash

#!/bin/bash

BACKUP=backup_date
SOURCE=Arithmetic_Operators

echo "Taking backup from ${SOURCE} directory to backup directory ${BACKUP} .."

# Checking the source directory ${SOURCE} exists or not ! if not exists die
# Script is unsuccessful with exit status # 1

[ ! -d $SOURCE ] && echo "source directory $SOURCE not found"
exit 1

# Checking the backup directory ${BACKUP} exists or not ! if not exists die
# Script is unsuccessful with exit status # 2

[ ! -d $BACKUP ] && echo "backup directory $BACKUP not found"
exit 2

# Let Start the backing up

tar cvf $SOURCE $BACKUP 2> /wrong/logs.txt

if [ $? -ne 0 ]
then
   # die with unsuccessful shell script termination exit status # 3
   echo "An error occurred while making a source directory backup, see /wrong/logs.txt file".
   exit 3 
fi

这是我将源目录(Arithmetic_Operators)备份到目标目录(backup_date)的脚本,在运行脚本时我的脚本以消息

结束
  

从Arithmetic_Operators目录备份到备份目录backup_date ..
  源目录未找到Arithmetic_Operators

我错误地说这个脚本没有运行的原因你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这些行意味着脚本无条件退出:

[ ! -d $SOURCE ] && echo "source directory $SOURCE not found"
exit 1

你可能意味着:

if [ ! -d $SOURCE ]
then
    echo "source directory $SOURCE not found" >&2
    exit 1
fi

或者也许:

[ ! -d $SOURCE ] && { echo "source directory $SOURCE not found" >&2; exit 1; }

请注意,错误消息应发送到标准错误,而不是标准输出。在消息中包含脚本名称($0)并不是一个坏主意;它有助于识别生成/检测到问题的脚本。

检查$BACKUP目录后,您遇到了类似的问题。

另外,作为一般规则,用双引号括起变量引用:

[ ! -d "$SOURCE" ] && { echo "source directory $SOURCE not found" >&2; exit 1; }

(当然,第二个引用已在双引号内。)