Linux – Replace Symbolic Links with Files

bashlinux

Is there an easy way to replace all symbolic links with the file they link to?

Best Answer

For some definitions of "easy":

#!/bin/sh
set -e
for link; do
    test -h "$link" || continue

    dir=$(dirname "$link")
    reltarget=$(readlink "$link")
    case $reltarget in
        /*) abstarget=$reltarget;;
        *)  abstarget=$dir/$reltarget;;
    esac

    rm -fv "$link"
    cp -afv "$abstarget" "$link" || {
        # on failure, restore the symlink
        rm -rfv "$link"
        ln -sfv "$reltarget" "$link"
    }
done

Run this script with link names as arguments, e.g. through find . -type l -exec /path/tos/script {} +

Related Question