繁体   English   中英

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

[英]Bash script to copy file from one directory to other directory

我想自动创建目录而无需从键盘输入数据。

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

您可以将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 {} \;

还有一个冗长的示例,向您展示了可以在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM