kakts-log

programming について調べたことを整理していきます

シンボリックリンク一覧の中から、指定したファイルを参照しているものを探す

概要

下記のように、a.txtのファイルを実体とし、それを参照したシンボリックリンクが2つ(b.txt, t/c.txt)あるとする。

この場合、a.txtを参照したシンボリックリンクを見つけたい場合、findコマンドを使うことで実現できます。 - b.txt - t/c.txt

$tree
.
├── a.txt
├── b.txt -> a.txt
└── t
    └── c.txt -> a.txt

ここでは簡単にするためにシンプルなファイル構造にしていて、ls コマンドでも見つけれますが、本当はいろんなところにシンボリックリンクが散らばっている場合に有効です。

コマンド

hoge.txtというファイルを参照しているシンボリックリンクをルート配下から探す場合は、下記コマンドで実現できます。

find / -type l -ls | grep hoge.txt

方法

所定ディレクトリ配下のシンボリックリンクを表示させる

findコマンドで、所定のディレクトリ配下のシンボリックリンクを表示するには、 find / -type l で可能です。

-type に lを指定すると、シンボリックリンクファイルを探すように設定できます。 manによってドキュメントを見てみると、下記のようになっています。ディレクトリや通常ファイル、FIFOなど、ファイルタイプを指定できます。

man find
     -type t
             True if the file is of the specified type.  Possible file types are as follows:

             b       block special
             c       character special
             d       directory
             f       regular file
             l       symbolic link
             p       FIFO
             s       socket
➜  misc find . -type l
./t/c.txt
./b.txt

ただし、ここではシンボリックリンクがどこを参照しているかわかりません。

表示されたシンボリックリンクの詳細を表示したい

ここで、見つかったファイルの情報を表示するには -lsオプションを付与します。

     -ls     This primary always evaluates to true.  The following information for the current file is written to standard output: its inode number, size in
             512-byte blocks, file permissions, number of hard links, owner, group, size in bytes, last modification time, and pathname.  If the file is a
             block or character special file, the device number will be displayed instead of the size in bytes.  If the file is a symbolic link, the pathname
             of the linked-to file will be displayed preceded by “->”.  The format is identical to that produced by “ls -dgils”.

このオプションにより、ファイルのinode番号や、権限、ユーザ、オーナー、シンボリックリンクのファイルパス・参照先のファイルも表示できます。

➜   find . -type l -ls
11758148        0 lrwxr-xr-x    1 user      staff                   5  6 14 00:44 ./misc/t/c.txt -> a.txt
11758122        0 lrwxr-xr-x    1 user      staff                   5  6 14 00:43 ./misc/b.txt -> a.txt
...
6791125        0 lrwxr-xr-x    1 user      staff                   8  2 11 00:46 ./c-unix-programming/symlinktest.txt -> test.txt

ファイル構成によっては、いろんなシンボリックリンクが表示されます。

指定したファイルを参照しているシンボリックリンクを表示させる。

上記の find . -type l -ls の結果から、指定したファイルを参照しているものをフィルターする場合、grepを使います。

 find . -type l -ls | grep a.xt
11758148        0 lrwxr-xr-x    1 user      staff                   5  6 14 00:44 ./misc/t/c.txt -> a.txt
11758122        0 lrwxr-xr-x    1 user      staff                   5  6 14 00:43 ./misc/b.txt -> a.txt

これで完了です。