15

I am wanting to move (not just copy) a group of files/directories to a different directory some of which have name clashes with files/directories in the target directory. My main objective is to move the files, so I can tolerate the non-empty directory being overwritten.

I am currently using mv ... destination however, occasionally I get

mv: cannot move `target' to /destination/target': Directory not empty

I tried mv -f ... destination with no success and since I want the files to be gone from their original location, rsync doesn't seem to be appropriate.

As a bonus, is there a good solution for preserving the files intended to be overwritten somehow maybe by renaming?

  • And what error do you get when you try your mv command? – suspectus Jan 4 '14 at 10:07
  • You explicitly say that rsync is not what you want; why did you tag this with rsync? – DopeGhoti Jan 4 '14 at 10:12
  • @DopeGhoti I said it doesn't seem appropriate, but I am willing to be shown otherwise. – user1227038 Jan 4 '14 at 10:42
  • @suspectus Updated question. – user1227038 Jan 4 '14 at 10:53
  • 1
    if you use use mv --backup=numbered or one of the other options for the --backup switch, then mv will complete the merge and preserve the files intended to be overwritten – bsd Jan 4 '14 at 11:11
18

If you use mv --backup=numbered
(or one of the other options for the --backup switch),
then mv will complete the merge and preserve the files intended to be overwritten.

1
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
SRC=/path/to/source
DST=/path/to/destination

for item in $SRC/*; do
    if [[ -f "$DST/$(basename "$item")" ]]; then
        newitem=$(basename $item)_old
        while [[ -f "$DST/$newitem" ]]; do
            newitem=${newitem}_old
        done
        mv "$DST/$(basename $item)" "$DST/$newitem"
    fi
    mv "$item" "$DST/$(basename $item)"
done
  • Instead of this script, one could directly run the cp followed by the mv command. – reza.safiyat Oct 5 '15 at 12:19

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.