Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is it possible to construct a command that will move the file to another directory and if the same file is already there, generate some random string that is not in the name of some file in the directory and rename the file to this random string?

I know the mv -i command, so I do it manually and files that are contained rename to something else.

thank you

share|improve this question

2 Answers 2

up vote 7 down vote accepted
mv -b file destination/

should do the trick.

mv --backup=TYPE

will act like the type says, it is either of the following:

none, off       never make backups (even if --backup is given)
numbered, t     make numbered backups
existing, nil   numbered if numbered backups exist, simple otherwise
simple, never   always make simple backups
share|improve this answer
    
I tried it as follows mv -b file destination/ . Now in the destination is file and file~ . I have another file named file. I used the command mv -b file destination/ and one file was lost, in destination there is only file and file~. I expected there will be file~~ too. –  xralf Nov 3 '11 at 11:34
5  
Try: mv --backup=numbered file destination/ instead. –  ckk Nov 3 '11 at 12:21
2  
Note that this renames the existing file at the destination, rather than creating a new name for the file being moved. (It's not clear whether this is acceptable for what you're asking) –  Random832 Nov 3 '11 at 17:20
    
@Random832 This is acceptable for me. –  xralf Nov 3 '11 at 18:43

There's no standard or common single-step command. Here's a two-step process, relying on the non-standard but common mktemp.

tmp=$(TMPDIR=$(dirname -- "$destination") mktemp -t)
mv -- "$source" "$tmp"
echo n | mv -i -- "$tmp" "$destination"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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