我有两个名为A和B的文件夹,位于同一台计算机上的不同路径中.当我将任何新文件添加到文件夹A中时,我想自动将其复制到文件夹B.
我的文件夹:
/auto/std1/nat1/A
/auto/std2/nat2/B
我目前要做的是复制文件:
cp -r A B
但是我希望这个过程在后台自动运行,用于A到B中的每个新文件和文件夹.
添加了问题/问题
在复制文件时,我希望对某些文件类型执行特定操作,例如:当我在文件夹A中有一个zip文件时,我希望它能自动在文件夹B中解压缩该文件.
这是在CentOS 7`系统上.
解决方法:
根据您的红利问题,在我下面提供的shell脚本中的rsync命令下面添加以下行.我在评论中写了这个,但我会正式将它添加到我的答案中:
find /auto/std2/nat2/B -name '*.zip' -exec sh -c 'unzip -d `dirname {}` {}' ';'
这将处理从文件夹/ auto / std2 / nat2 / A通过rsync复制到/ auto / std2 / nat2 / B的所有zip文件解压缩
如果你安装了rsync,为什么不只是cron它并让rsync管理文件镜像?
创建脚本myrsyncscript.sh
别忘了让它可执行:chmod 700 myrsyncscript.sh
#!/bin/sh
LOCKFILE=/tmp/.hiddenrsync.lock
if [ -e $LOCKFILE ]
then
echo "Lockfile exists, process currently running."
echo "If no processes exist, remove $LOCKFILE to clear."
echo "Exiting..."
# mailx -s "Rsync Lock - Lock File found" myemail@domain.com <<+
#Lockfile exists, process currently running.
#If no processes exist, remove $LOCKFILE to clear.
#+
exit
fi
touch $LOCKFILE
timestamp=`date +%Y-%m-%d::%H:%M:%s`
echo "Process started at: $timestamp" >> $LOCKFILE
## Run Rsync if no Lockfile
rsync -a --no-compress /auto/std1/nat1/A /auto/std2/nat2/B
echo "Task Finished, removing lock file now at `date +%Y-%m-%d::%H:%M:%s`"
rm $LOCKFILE
选项细分:
-a is for archive, which preserves ownership, permissions etc.
--no-compress as there's no lack of bandwidth between local devices
您可能会考虑的其他选项man rsync
:
–ignore-existing
skip updating files that exist on receiver
–update
This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file’s, it will be updated if the sizes are different.)
Note that this does not affect the copying of symlinks or other special files. Also, a difference of file format between the sender and receiver is always considered to be important enough for an update, no matter what date is on the objects. In other words, if the source has a directory where the destination has a file, the transfer would occur regardless of the timestamps.This option is a transfer rule, not an exclude, so it doesn’t affect the data that goes into the file-lists, and thus it doesn’t affect deletions. It just limits the files that the receiver requests to be transferred.
像这样将它添加到cron,并将频率设置为您感觉最舒适的频率:
用crontab -e打开cron并添加如下:
### Every 5 minutes
*/5 * * * * /path/to/my/script/myrsyncscript.sh > /path/to/my/logfile 2>&1
# * * * * * command to execute
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)