make a backup of each existing destination file

The man page does say that it works on file. It doesn't seem to have any effect on directories. Is there anyway to make this work with directories as well? I want the destination directory, if it exists, to be backed up in the same way that a file would be backed up.

  • What does "work" mean for a directory? Are you trying to back up the information about the directory itself, or are you trying to organize the backed-up files into a separate back-up directory (instead of having each file backed up in the directory in which it is found)? Either way, "cp" will not do this for you; you need to write a script. – Ian D. Allen Oct 14 '13 at 15:32
  • @IDAllen Yeah I have come to that same conclusion. Let me make the script an answer instead. – phunehehe Oct 15 '13 at 3:52
  • How would you then actually move or copy (multiple) files into a directory? – Kusalananda Mar 7 at 8:08

I have a feeling that there isn't, so I wrote this script which emulates the functionality:


if [ -e "$target" ]
    if [[ -e "$backup" ]]
        while [[ -e "$backup.$count" ]]; do let "count += 1"; done
    mv "$target" "$backup"
    echo "backup file $backup created."

# Normal cp or mv follows
  • I think you've written an archive and delete script, not a back-up script, since your script deletes the original directory (by renaming it). Your script comment about "file created" will mislead if it isn't a file. Depending on how you call your script (i.e. if you use it with find), you may find that it archives all the files under a directory before it archives the directory itself, or find will complain that you've just moved away a directory that it was about to walk - this may not be what you want. – Ian D. Allen Oct 17 '13 at 1:29
  • @IDAllen You misunderstood, this script is to be used in place of cp or mv, to make the --backup behavior applicable to directories. – phunehehe Oct 17 '13 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.