Linux: Find all symlinks of a given 'original' file? (reverse 'readlink')

后端 未结 6 2159
遥遥无期
遥遥无期 2020-12-04 11:33

Consider the following command line snippet:

$ cd /tmp/
$ mkdir dirA
$ mkdir dirB
$ echo \"the contents of the \'original\' file\" > orig.file
$ ls -la o         


        
6条回答
  •  天涯浪人
    2020-12-04 12:01

    Here's what I came up with. I'm doing this on OS X, which doesn't have readlink -f, so I had to use a helper function to replace it. If you have it a proper readlink -f you can use that instead. Also, the use of while ... done < <(find ...) is not strictly needed in this case, a simple find ... | while ... done would work; but if you ever wanted to do something like set a variable inside the loop (like a count of matching files), the pipe version would fail because the while loop would run in a subshell. Finally, note that I use find ... -type l so the loop only executes on symlinks, not other types of files.

    # Helper function 'cause my system doesn't have readlink -f
    readlink-f() {
        orig_dir="$(pwd)"
        f="$1"
        while [[ -L "$f" ]]; do
            cd "$(dirname "$f")"
            f="$(readlink "$(basename "$f")")"
        done
        cd "$(dirname "$f")"
        printf "%s\n" "$(pwd)/$(basename "$f")"
        cd "$orig_dir"
    }
    
    target_file="$(readlink-f "$target_file")" # make sure target is normalized
    
    while IFS= read -d '' linkfile; do
        if [[ "$(readlink-f "$linkfile")" == "$target_file" ]]; then 
            printf "%s\n" "$linkfile"
        fi
    done < <(find "$search_dir" -type l -print0)
    

提交回复
热议问题