force cp to copy on dangling symlinks

35

Solution 1

Make cp remove the target file before copying:

$ ln -s /random/file f              
$ cp -f a f                  
cp: not writing through dangling symlink ‘f’
$ cp --remove-destination a f
$ diff a f && echo yes
yes

From man cp:

--remove-destination
      remove  each existing destination file before attempting to open
      it (contrast with --force)

Solution 2

Just use unlink theSymLink where theSymLink is the actual symlink, then try again

Share:
35

Related videos on Youtube

Matthew Watson
Author by

Matthew Watson

Updated on September 18, 2022

Comments

  • Matthew Watson
    Matthew Watson almost 2 years

    I've been working on Java's WatchService API to monitor a file directory to see when files have been modified within it. (On Windows). I've got it so that I can see when files are modified.

    How can I see which process is responsible for file modification, and kill the process, even perhaps create a dump file too?

  • Eliah Kagan
    Eliah Kagan about 9 years
    This will work, but note that unlink has the same effect as (and thus no advantage compared to) the more commonly used rm. In particular, like rm foo, unlink foo will delete a file foo even when it is a regular file and not a symbolic link. Using unlink instead of rm (or mv --remove-destination ...) does not guard against accidental data loss.