Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'd like to recursively convert soft links to hard links in a directory. I've tried something like this:

for f in *; do (mv $f{,~} && ln $(readlink $f~) && rm $f~) done

…but it has two major problems:

  • not recursive
  • picks up files that are not symbolic links

It would be nice to somehow feed the above line to find -type l, but i'm not sure how to do that.

share|improve this question
1  
See also [this discussion][1] (cp -aH). [1]: unix.stackexchange.com/questions/94185/… –  Michael Shigorin Apr 23 at 12:08

1 Answer 1

up vote 7 down vote accepted

This command should work:

find -type l -exec bash -c 'ln -f "$(readlink -m "$0")" "$0"' {} \;

How it works:

  • find -type l finds all links in the current directory.

  • -exec bash -c '...' {} \; invokes bash to execute ....

    It passes {} – the name of the link that's currently being processed ‐ as an argument, which bash can access as $0.

  • readlink -m "$0" returns the absolute path of the symbolic link's destination.

  • ln -f "$(readlink -m "$0")" "$0" overwrites (-f) the symbolic link $0 with a hard link to its target.

If the link cannot be converted for some reason, it will remain untouched and ln will print an error message.

share|improve this answer
    
Regarding that last paragraph, wouldn't it suffice to specify absolute paths to bash and ln? –  Daniel Beck Mar 8 '13 at 14:42
2  
My problem was that readlink returns a relative path by default, but the -e switch fixes that. –  sudo Mar 8 '13 at 14:51

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.