I would like to know if there is any way a file can be moved only if the destination does not exist – in other words, move only if it does not lead to overwriting.
mv --update
seemed first to be the solution, however, if the timestamp of the source path is newer than the destination, move will overwrite it and all attempts to circumvent this by modifying the timestamp before the move will fail.
I need this behaviour to implement a simple file based lock where existence of a 'lock' file indicates that the lock is acquired.
Best Answer
You could use rsync with the
--ignore-existing
switch:However, I think this is not atomic. You can create advisory locks with
flock
to make sure the processes you control (Cooperating processes) won't write to it. But another process still could.The only way you can lock a file without the risk of a another process messing with it is to mount the filesystem with mandatory locking. From
<linux_kernel_source>/Documentation/filesystems/mandatory-locking.txt
: