Convert symbolic links into corresponding target files

6

3

I have several symlinks to other files in a directory. I want to convert these links into independent files.

Is there a command that does this?

Utkarsh Sinha

Posted 2012-05-04T17:07:22.733

Reputation: 1 327

Question was closed 2014-09-12T11:48:16.257

are they hard or soft (symbolic) links? – seanwatson – 2012-05-04T17:11:40.067

They're soft links - editing the question. – Utkarsh Sinha – 2012-05-04T17:16:33.223

I'm interested to know how to do this for hard links. – Craig McQueen – 2012-10-19T02:16:45.277

Answers

9

cp --remove-destination "$(readlink <symlink>)" <symlink>

Ignacio Vazquez-Abrams

Posted 2012-05-04T17:07:22.733

Reputation: 100 516

Freebsd doesn't have --remove-destionation and using -f wasn't working too. So, needed to orig = $(readlink <symlink>); rm <symlink>; cp $orig . – Alberto – 2019-05-10T08:33:23.900

That felt good! – Utkarsh Sinha – 2012-05-04T17:35:04.167

1

While Ignacio's is a good reply, I wanted to automate the process for every file that is a symlink in the current directory and subdirectories.

This does the trick:

find . -type l -exec cp \"{}\" \"{}.tmp$$\" \; -exec mv \"{}.tmp$$\" \"{}\" \;

Hope this helps!

Cris70

Posted 2012-05-04T17:07:22.733

Reputation: 61

0

The first way that comes to my mind would be to copy all of the links to new files then delete all of the links.

cp <link> <link>.new
rm <link>

Hopefully the files have some sort of common naming structure so you can use wildcarding and only run the commands once otherwise you might want to write a simple shell script

seanwatson

Posted 2012-05-04T17:07:22.733

Reputation: 246

That's what I've been doing till now. I was hoping unix would have some command that does this automatically. – Utkarsh Sinha – 2012-05-04T17:21:22.653

0

FYI: Mac OS X does not support the --remove-destination flag so I wrote a simple script to put in your /usr/bin directory:

FILE=$1
TEMP=$1".tmp"

mv $FILE $TEMP

if [ -e $TEMP ]
then
    cp "$(readlink $TEMP)" $FILE

    if [ -f $FILE ]
    then
        rm $TEMP
    else
        echo "unln failed."
    fi
fi

This one let's you use wildcards:

for FILE in "$@"
do
    TEMP=$FILE".tmp"

    if [ -h $FILE ]
    then
        mv $FILE $TEMP

        if [ -e $TEMP ]
        then
            cp "$(readlink $TEMP)" $FILE

            if [ -f $FILE ]
            then
                rm $TEMP
            else
                echo "unln failed for link: $FILE"
            fi
        fi
    fi
done

user41608

Posted 2012-05-04T17:07:22.733

Reputation: