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?

beli3ver
  • 164
  • 1
  • 5
  • 2
    Does this answer your question? [How can I "relink" a lot of broken symlinks?](https://unix.stackexchange.com/questions/18360/how-can-i-relink-a-lot-of-broken-symlinks) – user598527 Feb 17 '22 at 17:13

2 Answers2

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.

noAnton
  • 361
  • 1
  • 6
  • 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 Apr 08 '20 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 {} \;` – Toby Speight Feb 21 '22 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. – Toby Speight Feb 21 '22 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?

Gabriel Staples
  • 2,192
  • 1
  • 24
  • 31