1

I moved from an old webserver to a new one. Now some symlinks not working, because we changed the folder structur. I want to know if there is a easy way to repair these links? I found the links with this command:

find -L . -type l -ls

The links looks like this:

./example/vondercode/releases/example.com/2.0/www/img/uploads -> /home/example/vondercode/uploads
./example2/www/img/uploads -> /home/example2/vondercode/uploads

Now the links must look like this:

./example/vondercode/releases/example.com/2.0/www/img/uploads -> /var/www/html/example/vondercode/uploads
./example2/www/img/uploads -> /var/www/html/example2/vondercode/uploads

So easy to say, all /home should be replaced by /var/www/html Is this possible?

1

2 Answers 2

2

if it is "just replace /home with /var/www/html" then this approach should work:

find . -type l -exec sh -c 'lnk="{}"; target="$(readlink '{}' | sed 's#/home#/var/www/html#')"; unlink "${lnk}"; ln -s "${target}" "${lnk}" ' \;

Thanks for Toby Speight to point out that the first version did not work as expected - this is fixed now.

3
  • 1
    You'll need to remove the existing links or use ln -sf to overwrite them. However, since this can be destructive if it goes wrong, I would suggest first echoing the commands to make sure they do what you expect and then running them.
    – terdon
    Commented Apr 8, 2020 at 10:20
  • This is vulnerable to filename injection - prefer to pass {} as a shell script argument: find . -type l -exec sh -c 'p=$(realpath "$1"); rm "$1" && ln -s "${p/#\/home//var/www/html}" "$1"' sh {} \; Commented Feb 21, 2022 at 11:50
  • Actually, it's completely broken, as realpath {} is executed far too early - this will just remove all your links and the ln commands will fail. Commented Feb 21, 2022 at 11:53
0

I wrote a tool. You can use it like this:

fix_broken_symlinks . /home /var/www/html --force

See full details in my main answer here: How can I "relink" a lot of broken symlinks?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .