How to backup files in multiple directories with git?

If you don't mind moving the files...

You could do this by moving the files into a git repository, and symlinking them to their old locations; you'd end up with

  • ~/gitrepo/somedir/otherdir/file1 moved from ~/somedir/otherdir/file1
  • ~/gitrepo/otherdir/somedir/file2 moved from ~/otherdir/somedir/file2
  • a symlink from ~/somedir/otherdir/file1 to ~/gitrepo/somedir/otherdir/file1
  • a symlink from ~/otherdir/somedir/file2 to ~/gitrepo/otherdir/somedir/file2

You can then safely commit the files in the git repository, and manipulate them using git, and anything using the old file paths will see whatever is current in the git workspace. Linking the files the other way round, or using hard links, would be dangerous because any git operation which re-writes the file (changing branches, reverting to a previous version...) would break the link. (Hopefully this explains why hard links aren't really a viable solution.)

With this kind of scenario you'll have to be careful with programs which re-write files completely, breaking links; many text editors do this, as do tools such as sed -i etc. A safer approach would be to move the entire folders into the git repository, and symlink the directories.

If you want to keep the files in place...

Another possibility is to create a git repository in your home directory, tell git to ignore everything, and then forcefully add the files you do want to track:

cd
git init
echo '*' > .gitignore
git add -f .gitignore
git commit -m "Initialise repository and ignore everything"
git add -f somedir/otherdir/file1
git commit -m "Add file1"
git add -f otherdir/somedir/file2
git commit -m "Add file2"

Once you've done this, you'll easily be able to track changes to files you've explicitly added, but git won't consider new files. With this setup it should also be safe to have other git repositories in subdirectories of your home directory, but I haven't checked in detail...

Tags:

Git

Backup