vote up 1 vote down star

Question relates to shell-scripting in bash.

How to check with a script which files within the current directory are soft links?

In case I have used the wrong term, when I say soft links, I am referring to files created using ln -s.

The only thing I have managed to think of is to evaluate ls -la as an expression, and parse its results, but obviously this is not the best solution.

flag

80% accept rate
They're referred to as "symbolic links" (as opposed to "hard links"). – Dennis Williamson Nov 16 at 12:40
Righto, I knew I probably got the term wrong, thanks for the heads up – bguiz Nov 17 at 11:24
Soft link is just fine as well, but with a space. :-) (en.wikipedia.org/wiki/Symbolic_link) – Arjan van Bentem Nov 17 at 12:20

2 Answers

vote up 7 vote down check

See 'CONDITIONAL EXPRESSIONS' in man bash - in this case you want -h:

for file in *
do
  if [ -h $file ]; then
    echo $file
  fi
done
link|flag
faqs.org/docs/bashman/bashref_68.html - For conditional expressions makes for a better read than the man page. – Manos Dilaverakis Nov 16 at 11:20
Thanks @Polsy and @Manos! test -h is what I wanted! – bguiz Nov 17 at 11:28
vote up 1 vote down

You might not really need a script. To show any symbolic links in just the current folder, without recursing into any child folder:

find . -maxdepth 1 -type l -print

Or, to get some more info:

find . -maxdepth 1 -type l -print0 | xargs -0 ls -ld

To tell if a file is a symbolic link, one can use readlink, which will output nothing if it's not a symbolic link. The following example is not quite useful, but shows how readlink ignores normal files and folders:

find . -maxdepth 1 -print0 | xargs -0 readlink
link|flag
I liked Polsy's answer better, still +1 for you, since I might need to do it outside a shell script some day. – bguiz Nov 17 at 11:30

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.