evilive
evilive

Reputation: 996

Using find to delete symbolic links except those which point to directories

At the moment I recursively remove all softlinks from my current working directory like this:

find . -type l -delete

But I don't want to remove symlinks pointing to a directory anymore.

Is there simple way to customize the find command or do I have to omit the -delete and script something to inspect every found softlink "myself" before removing?

Upvotes: 1

Views: 1147

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

As already suggested in the comments, you can use the test utility for this; but you don't need readlink because test -d always resolves symbolic links.

# replace -print with -exec rm {} +
find . -type l ! -exec test -d {} \; -print

It might be slow due to the overhead from spawning a new process for each symlink though. If that's a problem, you can incorporate a small shell script in your find command to process them in bulks.

find . -type l -exec sh -c '
for link; do
  shift
  if ! test -d "$link"; then
    set "$@" "$link"
  fi
done
# remove echo
echo rm "$@"' sh {} +

Or, if you have GNU find installed, you can utilize the -xtype primary.

# replace -print with -delete
find -type l ! -xtype d -print

Upvotes: 2

Related Questions