Remove file, but only if it's a symlink
$ rm_if_link(){ [ ! -L "$1" ] || rm -v "$1"; }
#test
$ touch nonlink; ln -s link
$ rm_if_link nonlink
$ rm_if_link link
removed 'link'
You can use find
and its -type l
test condition (which tests to see if the object found is a link or not)
For example, if you have a file called foo
in the current directory, you could do this:
$ find . -type l -iname "foo" -delete
You might be able to simplify that with just:
$ find . -maxdepth 1 -type l -delete
Which would delete all symlinks in the current directory.
Warning:
The -delete
option in find
is really really dangerous. BE SURE TO PLACE IT AT THE END OF THE FIND COMMAND. If you misplace it, it will delete everything it finds regardless of whether the results match your conditional.
As suggested in the comments, a safer option might be to use find
and rm -i
(which forces you to confirm file removal) in conjuction:
$ $ find . -type l -iname "foo" | xargs rm -i
Personally I use -exec trash {} \;
to temporarily delete files, because I, like yourself, have been burned by rm
in the past. Double goes for a misplaced -delete
flag.
http://slackermedia.ml/trashy
zsh -c 'rm foo(@)'
@
is a glob qualifier; the pattern foo(@)
matches what foo
matches, but only the symbolic links.
foo(-@)
would only match broken symbolic links. foo(@,L0)
would match only symbolic links and empty files.
Of course, if you're running zsh in the first place, you just need to type rm foo(@)
. You do need to take care not to press Enter before typing (@)
.