11

To backup existing files with number suffixes, I can do the following:

cp --backup=numbered afile /path/to/dest

But this does not apply when I try to do the same with a folder:

cp -R --backup=numbered afolder /path/to/dest

How can I achieve this?


Maybe I should demonstrate a bit what I want to achieve. First we have two dirs:

ls -ld source container
drwxrwxr-x 6 kaiyin kaiyin 4096 Nov 29 22:11 container
drwxrwxr-x 2 kaiyin kaiyin 4096 Nov 29 22:09 source

Then we do this:

myPerfectCp -R --backup=numbered source container/
myPerfectCp -R --backup=numbered source container/
myPerfectCp -R --backup=numbered source container/
myPerfectCp -R --backup=numbered source container/

Ideally I want this result:

tree container/
container/
├── source
├── source.~1~
├── source.~2~
└── source.~3~
muru
  • 72,889
qed
  • 2,669
  • Just a thought: I would explain "backup" as: "* keeping snapshots of files at certain times". The, directories themselves don't change - it's their content that changes. I understand your question as: "How to create consecutively numbered directories that contain backups of files*" -> instead of one directory keeping backup.~1~, backup~2~ etc. you want dir~1~ containing backup~1~, followed dir~2~ containing backup~2~ and so on, thus tracking each change of state in a separate directory. Is this right? – erch Nov 29 '13 at 18:11

2 Answers2

2

Try:

find source -type f -exec cp --backup=numbered -- {} container/ \;
cuonglm
  • 153,898
1

Although this could be done in bash, I'm more a python guy, so here goes my proposal:

#!/usr/bin/env python
import glob
import os
import sys


def cpdir(source, target):
    if target.endswith('/'):
        if not os.path.isdir(target):
            print "Target directory doesn't exist: %s" % target
            sys.exit(1)
        target += source
    if '--backup=numbered' in sys.argv:
        dirs = glob.glob(target + '.~*~')
        if not dirs:
            num = 1
        else:
            num = max([int(dir.split('~')[-2]) for dir in dirs]) + 1
        target += '.~%s~' % num
    cmd = 'cp -a %s %s' % (source, target)
    #print cmd
    rv = os.system(cmd)
    sys.exit(rv)

def main():
    if len(sys.argv) < 3:
        print "Usage: %s [--backup=numbered] <source> <dest>" % sys.argv[0]
        sys.exit(1)
    source = sys.argv[1]
    target = sys.argv[2]
    return cpdir(source, target)

if __name__ == '__main__':
    sys.exit(main())
muru
  • 72,889
erny
  • 576