6

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

3 Answers 3

12
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 
4
  • 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. Commented Nov 3, 2011 at 11:34
  • 5
    Try: mv --backup=numbered file destination/ instead. Commented Nov 3, 2011 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) Commented Nov 3, 2011 at 17:20
  • @Random832 This is acceptable for me. Commented Nov 3, 2011 at 18:43
1

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" 
1
$ mv -fv --backup=simple file1.txt archive/ ‘file1.txt’ -> ‘archive/file1.txt’ (backup: ‘archive/file1.txt~’) $ ll archive/ -rw-r--r-- 1 root root 8 Dec 10 11:06 file1.txt -rw-r--r-- 1 root root 10 Dec 10 11:05 file1.txt~ 

The mv above will move the file1.txt to archive/ directory and rename the existing archive/file1.txt to file1.txt~ in case of any file name conflict. It keeps only one backup file ‘archive/file1.txt~’ if you run it again.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.