I think this is best explain with an example:

lrwxrwxrwx 1 root   root      21 Mar 31 08:44 awk -> /etc/alternatives/awk*
-rwxr-xr-x 1 root   root     45K Apr  8  2015 b43-fwcutter*
lrwxrwxrwx 1 root   root      35 Apr  1 21:42 backup-config -> /home/myuser/scripts/backup-config.sh
lrwxrwxrwx 1 root   root      37 Apr  1 21:42 backup-to-server -> /home/myuser/scripts/backup-to-server.sh

I want to delete all the symlinks that pointing to files inside /home/myuser/scripts.

In this example. I want backup-config and backup-to-server to get deleted.


ps. I have other symlinks in the folder that I want to delete but it doesn't start with backup so I cannot really use a pattern.


Loop over the files and match the symlinks against a pattern. This should work for direct links with absolute paths (not something like ../../something, or things that jump through multiple symlinks.)

for f in * ; do
    [ -L "$f" ] || continue;                      # skip anything but symlinks
    l=$(readlink "$f")                            # read the link contents
    case "$l" in 
        /home/myuser/scripts/*) echo rm "$f" ;;   # match against a pattern

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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