Search code examples
linuxshellsymlink

Deleting symbolic links using a shell script


So I wanted to create a shell script which goes through a directory and deletes any unused symbolic links/links to files which no longer exist. I done a bit of research and found ways to do it in command line but couldn't find a way to create a shell script which does this.

I wanted to be able to do ./script.sh dir_name and it deletes the symbolic links in that directory. If someone could help me create this or let me know how it might be possible it would help a lot <3


Solution

  • Here's a quick bash script I wrote to accomplish what you're looking for:

    #!/bin/bash
    
    dir="$1"
    
    if [[ -z "$dir" ]]; then
        echo "Error, missing argument for directory to remove symlinks from"
        exit 1
    fi
    
    find "$dir" -xtype l -delete