Validate Symlinks on Mac OS X

I'm working on an Folder Action to automatically create some symlinks, and needed to account for a finite number of temporary files, which requires that I know if a symlink is valid or not.

Apple's Developer Tools ships with a utility called GetFileInfo that does just the trick.

/Developer/Tools/GetFileInfo -aa _SYMLINK_ >/dev/null 2>&1 ; echo $?

This will return 0 if the symlink (_SYMLINK_) points to a valid file, and as near as I can tell, 3 if the file does not exist.

Bonus

On Linux you can find the filenames of all broken symlinks in a given directory using find/xargs/grep/sed with

find . -type l -print0 | xargs -0 file | grep "broken symbolic" | sed -e 's/^\|: *broken symbolic.*$/"/g'

The only piece that doesn't work on OS X is the sed regexp (which I'm too lazy to fix), but you can kind of work around that with cut, as long as your symlink filenames don't contain a colon.

find . -type l -print0 | xargs -0 file | grep "broken symbolic" | cut -d':' -f1

 

Tags: , , ,

Leave a Reply


© 2007-2012, Corey Gilmore | Posts RSS Feed | Comments RSS Feed | Contact

 

The views expressed on these pages are mine alone and not those of any past or present employer. All information presented on this site was obtained lawfully and not through disclosure under the terms of an NDA.