Friday, June 26, 2015

clobber

mv --no-clobber option

Problem:

I'm writing a script in which I need to move files from one directory to another. However, some of the files have the same name, and I want to keep the older file, so I can't use --update. I'm moving files from the newer directory to the older directory, so what I'm looking for is a way to automatically not overwrite. Basically, I need the behavior of mv with the opposite of --force option. I can't use the --interactive option either, because I'm copying multiple files and I don't want mv to hang.

There's no reason I must use mv, I just assumed it'd be the easiest way to accomplish what I need. If there's an easier way that doesn't involve mv I'm open for suggestions.

After searching around a while I found this recent webpage which makes it seem as though mv will now have a --no-clobber option which will do exactly what I need. I'm running Ubuntu on this computer, so I'm sure the webpage is relevant, but mv doesn't like --no-clobber despite the fact that my system is updated.

So basically what I need is explained in the first paragraph. I want a script to move files from one directory to another and automatically NOT overwrite: the oppsite of --force.

Thanks in advance for any help or suggestions!
 
Solution:
 
Code:
fromdir=/path/to/original/files
destdir=/path/to/destination/directory

cd "$fromdir" || exit 1

for file in *
do
  [ -f "$destdir/$file" ] || mv "$file" "$destdir"
done

 The above code will work nicely.

The other possible solution is: 
 
bash: set -o clobber 
 
which will deny overwriting any files.

No comments:

Post a Comment