0

how would I be able to compare two directories' files and replace their timestamps if the files exist in both directories in bash script? For example, I have file1.txt in Directory1 and file1.txt in Directory2 (the directories are given as arguments) that have different timestamps, and I want to replace the newer timestamp with the older. How would I do that?

I already know that I should be using the touch command (https://askubuntu.com/questions/62492/how-can-i-change-the-date-modified-created-of-a-file) for that end, and also use -nt and -ot (compare file's date bash) for comparing the files, but since I'm fairly new to scripting, I'm having some trouble figuring out how to put all this together.

Community
  • 1
  • 1
  • "I'm having some trouble figuring out how to put all this together." Then show us what you have tried. You can surely try. Read the manual for syntax. https://www.gnu.org/software/bash/manual/bash.html – 4ae1e1 Dec 06 '15 at 12:35
  • @4ae1e1 I would gadly but unfirtunately I am on my phone at the moment! If it is still necessary I will post the code when I get back home. Sorry about that. – DefinitelyNotMe Dec 06 '15 at 12:43

1 Answers1

0

Backup your files. Try this:

cd "$1"
for i in *; do
  if [[ -e ../$2/$i ]]; then
    if  [[ $i -ot ../$2/$i ]]; then
      touch -r "$i" "../$2/$i"
    else
      touch -r "../$2/$i" "$i"
    fi
  fi
done
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Thank you for your swift answer! If the directories are passed as arguments, would I just have to replace Directory1 by $1 and Directory2 by $2? – DefinitelyNotMe Dec 06 '15 at 12:45