How do I delete a hard link?

You can delete it with rm as usual: rm NameOfFile. Note that with hard links there is no distinction between "the original file" and "the link to the file": you just have two names for the same file, and deleting just one of the names will not delete the other.


I have this script to remove redundant hard links. But take care - it is quite dangerous.

#!/bin/bash
clear
echo Reduce redundant hardlinks in the current folder
echo ------------------------------------------------
echo 
echo "  $(basename $0) [-R]"
echo "      -R means recursive"
echo 
read -p "You can break by pressing Ctrl+C"
echo
ask=1
if [ a$1 == "a-R" ]; then  recursive=" -R "; fi

for i in $(ls -i $recursive | awk '{print $1}' | uniq --repeated | sort); 
do 
    echo "Inode with multiple hardlinked files: $i"
    first=1
    for foundfile in $(find . -xdev -inum $i);
    do 
        if [ $first == 1 ]; then
            echo "  preserving the first file:  $foundfile"
            first=0
        else
            echo "  deleting the redundant file:    $foundfile"  
            #rm $foundfile  
        fi
    done 
    if [ $ask == 1 ]; then 
        read -p "Delete all the rest of redundant hardlinks without asking? y/N "
        if [ a${REPLY,,} == "ay" ]; then  ask=0; fi
    fi  
#   read -p "pause for sure"
    echo
done
echo "All redundant hardlins are removed."
echo

Tags:

Delete