We need to create a process that run continues and whenever a file is placed in a specific directory, the process detected this new file and replicated in another directory.
How can we implement a process that allows automatic replies to the new files?
Option 1: Use rsync from one directory to the other
Option 2: Use File::Monitor
Option 3: If you're on Linux, code something up in C using inotify
Option 4: (might miss files)
cd /incoming
while true
do
filename=$( basename $( ls -1t ) )
if [ ! -e /replicate/${filename} ]
then
cp /incoming/${filename} /replicate/.
fi
sleep 30
done
Obviously 'ls -1t' in 'filename=$( basename $( ls -1t ) )' returns more than one file name, a thing which basename can't handle with. Try:
cd /incoming
while filename in "$(ls -1t)"
do
if [ ! -e "/replicate/${filename}" ]
...
P.S. I didn't use basename at all, since /incoming may have subdirectories with files, which also should be taken into account while generating replicates
It work's,
one last question : How can i only list files from a directory (no need the files in the subdirectory), ie list files and exclude the directorys.
in such cases I'm usually using 'find' command. Below is one possible solution. (Here we need basename in one place, since 'find' adds relative path in front of found files)
# your source/target directory may change
# so save it better in a variable
SRC_DIR="/incoming/"
TRG_DIR="/replicate/"
# looking for all files in source directory
# dereferencing soft links, not going deeper in
# subdirs - just as you wanted :-)
for filename in $(find -L $SRC_DIR -maxdepth 1 -type f)
do
# looking if corresponding file does not exist in target directory
if ! test -e "${TRG_DIR}$(basename $filename)"
then
# copy if it doesn't
cp ${filename} ${TRG_DIR}
fi
# don't sleep on your workplace :-)
#sleep 30
done
I've commented 'sleep' because I think that it would be better to add the execution of your script to crontab.