Linux上使用Shell脚本复制结构相同的所有文件

2049人浏览 2020-09-09

需求

我们的需求是将目录中创建的所有文件复制到具有相同目录结构的其他目录。脚本将定期运行,搜索在源目录中创建的所有文件,并将其复制到目标目录。该脚本必须在目标目录上保持相同的目录结构。之后,更改目标目录上的权限。成功复制文件后,脚本必须从源目录中删除文件。

编写Shell脚本

首先在系统上创建一个Shell脚本并添加以下内容。将源目录和目标目录更新到正确的位置,如果您不想更改目标文件的权限,请将CHANGE_OWNERSHIP设置为0。

#!/bin/bash
 
#####################      Variables     #############################
 
### Set the proper source and destination directory location
 
SOURCE_DIR="/source/dir/"
DEST_DIR="/desination/dir/"
TMP_FILE=/tmp/copyfileslist.txt
 
### Set the username and group name to set permission on copied files
### Set CHANGE_OWNERSHIP to 1 to change ownership or 0 to unchanged it
 
CHANGE_OWNERSHIP=1
USER='root'
GROUP='root'
 
 
########### Do not edit below this until required  #################
 
### Test if source directory exists
### The script will stop if source not exists
 
if [ -d "${SOURCE_DIR}" ]; then
        echo "Source directory found"
else
        echo "Source directory not found. Please check above variables are set correctly"
        echo "script exited"
        exit 1
fi
 
### Test if destination directory exists
### The script will create destination directory if not exists.
### If failed to create directory, the script will terminate
 
if [ -d "${DEST_DIR}" ]; then
        echo "Destination directory found, all ok"
else
        echo "Destination directory not found, creating now"
        mkdir -p "${DEST_DIR}"
        if [ $? -eq 0 ]; then
                echo "Successfully created destination directory."
        else
                echo "Failed to create destination directory. Script exited"
                exit 1
        fi
fi
 
 
### Copy all files available on source directory
### After successfully copying file remove it from source directory.
 
cd "${SOURCE_DIR}"
 
if [ $? -eq 0 ]; then
        find . -type f > ${TMP_FILE}
 
        while read CURRENT_FILE_NAME
        do
                cp --parents "${CURRENT_FILE_NAME}" "${DEST_DIR}"
                if [ $? -eq 0 ]; then
                        echo "File ${CURRENT_FILE_NAME} successfully copied."
                        rm -f "${CURRENT_FILE_NAME}"
                else
                        echo "File ${CURRENT_FILE_NAME} failed to copy"
                fi
        done < ${TMP_FILE}
        rm -f ${TMP_FILE}
fi
 
 
## Set the permissions after copying files
 
if [ ${CHANGE_OWNERSHIP} -eq 1 ]; then
 sudo chmod 775 -R "${DEST_DIR}"
 sudo chown ${USER}:${GROUP} -R "${DEST_DIR}"
fi
 
###################  End of Script  ###################################

使用wq保存文件,然后将此文件权限设置为可执行文件。

chmod + x script.sh

大功告成!

推荐文章

linux上设置crontab,达到秒级执行的定时任务
2020-09-16
设置谷歌云服务器使用ssh密码方式远程连接服务器
2020-09-09
Linux查看IO占用过高的进程。
2021-11-22
Golang项目部署守护运行 使用bash脚本校验进程是否后台运行 并停止/启动/重启/编译运行go项目(后台守护运行)
2021-08-06
搜索文章