简体   繁体   中英

Bash script to copy file from one directory to other directory

I want to automatically create a directory without entering data from the keyboard.

Where should I place my *.war* file for backup then I have to copy this file to another directory here I should remove existing file and copy this new file in * * .

You can use the rsync command with the argument --delete , example:

folder a: 2019-05-21.war

folder b: 2019-05-15.war

when you run rsync it will erase whatever is different in the destination folder.

script examples:

#!/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 {} \;

One a little more verbose example showing you typical things that you can do easily in a shell script.

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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