In my opinion corn job is better alternative than any infinite loop. I am assuming the ~/backup
folder already exists. One can set a corn job to run the following script at an interval of n
minutes depending on their need. It will serve the purpose.
Run the script at an interval of 5 minutes
open user's crontab (cron configuration file) from a terminal as, crontab -e
. Add the following line to run the script at an interval of 5 minutes,
*/5 * * * * /path/to/script
Don't forget to give the script the execution permission : chmod u+x /path/to/script
The script
#!/bin/bash
msrc="/home/$USER"
mdst="/home/$USER/backup"
msrcfile="workfile"
mnewfile="$msrcfile"-$(date +"%Y-%m-%d-%H:%M")
checkfile="$(for i in "$mdst"/*; do echo "$i"; done | xargs ls -1t > /dev/null 2>&1 | head -1)"
if [[ "$msrc"/"$msrcfile" -nt "$checkfile" ]]; then
cp "$msrc"/"$msrcfile" "$mdst"/"$mnewfile"
fi
From man bash
:
CONDITIONAL EXPRESSIONS
file1 -nt file2
True if file1 is newer (according to modification date) than file2, or if file1
exists and file2 does not.
From man ls
:
-t sort by modification time, newest first