Bash脚本将文件从一个目录复制到另一目录

时间:2019-05-21 12:28:41

标签: bash shell scripting

我想自动创建目录而不用键盘输入数据。

我应将我的 *。war * 文件放在哪里进行备份,然后我必须将此文件复制到另一个目录中,我应该删除现有文件,然后将此新文件复制到 * * < / em>。

2 个答案:

答案 0 :(得分:1)

您可以将rsync命令与参数--delete一起使用,例如:

folder a: 2019-05-21.war

folder b: 2019-05-15.war

运行rsync时,它将擦除目标文件夹中的所有不同内容。

脚本示例:

#!/bin/bash
origin_dir="/opt/a"
dest_dir="/opt/b"
log=$(date +"/tmp/%F-bkp.log" -u)

rsync -avz --delete $a/ $b/ >> $log 2>&1

#if you want to keep backup for less than a week, delete the older files in origin

[ -d "$a/" ] && find $a/ -type f -name '*.war' -mtime +6 -exec rm {} \;

答案 1 :(得分:0)

还有一个冗长的示例,向您展示了可以在Shell脚本中轻松完成的典型操作。

#!/bin/bash

trap f_cleanup 2                # clean-up when getting signal
PRG=`basename $0`               # get the name of this script without path

DEST=$HOME/dest                 # XXX customize this: the target directory

#
# F U N C T I O N S
#

function f_usage()
{
        echo "$PRG - copy a file to destination directory ($DEST)"
        echo "Usage: $PRG filename"
        exit 1
}

function f_cleanup()
{
        echo ">>> Caught Signal, cleaning up.."
        rm -f $DEST/$1
        exit 1
}

#
# M A I N
#

case $# in
        1)
                FILE=$1         # command line argument is the file to be copied
                ;;
        *)
                echo "$PRG: wrong number of arguments ($#), expected 1"
                f_usage
                ;;
esac


while getopts "h?" opt; do
        case "$opt" in
                h|\?)
                        f_usage
                        ;;
        esac
done

if [ ! -f $FILE ]; then
        echo "$PRG: error: file not found ($FILE)" && exit 1
fi

if [ ! -d $DEST ]; then
        echo "$PRG: warning: dest dir ($DEST) does not exist, trying to create it.."
        mkdir -p $DEST && echo "$PRG: dest dir ($DEST) successfully created"
        if [ $? -ne 0 ]; then
                echo "$PRG: error: dest dir ($DEST) could not be created"
                exit 1
        fi
fi

cp -p $FILE $DEST
RET=$?                          # return status of copy command

case $RET in
        0)      echo "$PRG: copying $FILE to $DEST was successful"
                rm $FILE
                ;;
        *)      echo "$PRG: copying $FILE to $DEST was not successful"
                exit 1
                ;;
esac