0

Does anyone know the specific command for how to show the file with most hard links in a directory on terminal on unix?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146

1 Answers1

0

This solution works for all filenames (including ones with newlines in them), skips non-files, and prints the paths of all files that have the maximum number of links:

dir=$1

# Support empty directories and directories containing files whose
# names begin with '.'
shopt -s nullglob dotglob

declare -i maxlinks=0 numlinks
maxlinks_paths=()
for path in "$dir"/* ; do
    [[ -f $path ]] || continue  # skip non-files
    numlinks=$(stat --format '%h' -- "$path")
    if (( numlinks > maxlinks )) ; then
        maxlinks=numlinks
        maxlinks_paths=( "$path" )
    elif (( numlinks == maxlinks )) ; then
        maxlinks_paths+=( "$path" )
    fi
done

# Print results with printf and '%q' to quote unusual filenames
(( ${#maxlinks_paths[*]} > 0 )) && printf '%q\n' "${maxlinks_paths[@]}"
pjh
  • 6,388
  • 2
  • 16
  • 17