简体   繁体   中英

Bash - broken symlinks

I'm having troubles with writing bash script under Debian. I have folder which contains some more folders and files (It's a tree of folders). This tree contains symlinks. I want to go recursively through whole structure, detect broken symlinks a print them (not their target, but the links itself) in this fasion (absolute paths):

/tmp/Foo/Bar/symlink1
/tmp/Foo/symlink2
/tmp/Foo/Goo/symlink3

But I do not want and can't use classic

find -L $(path) -type l

Because this follows the correct links out of given structure and detects broken links outside of structure and I don't want these in my printout since I want only detect broken symlinks inside of my structure that is given in $(path) and all of it subdirectories. Could you please help me out? I have feeling that this will require some black magic with readlink and some loop, but I have no idea how. Thanks for advice! :)

The following command will do the job without following symlinks:

find /tmp/ -type l -printf '%p|' -exec stat -L {} \; 2>&1 | grep 'No such' | cut -d'|' -f1

The -L option of stat follows the link by checking the file behind it (do not confuse it with -L option of find however). When the link is not found, you get error:

stat: cannot stat `./symlink': No such file or directory

However, we want to print the name of the file as well, so that's why we use -printf '%p|' . The pipe here is used just as a delimiter (I doubt that you have files with pipe in their name), to separate the file name from the stat error that would be printed otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM