目の前に僕らの道がある

勉強会とか、技術的にはまったことのメモ

シンボリックリンクとハードリンク

ハードリンク

1つのファイルに対して複数の名前をつけるリンク方法。Soralisの場合、、同じスライス内でしか作れない。
ls -lで表示されるi-nodeの参照カウントが2以上ならハードリンクです。

ln 参照元ファイル ハードリンクファイル

シンボリックリンク

特定ファイルに対する位置情報を記録するリンク方法。windowでいうショートカットのイメージ。一般的にリンクといったらこっちを指す方が多い。
参照元ファイル削除するとファイルにアクセスすることができなくなります。

ln -s 参照元ファイル シンボリックリンクファイル

実験

vm-ubu01% ls -l 
合計 4
-rw-r--r-- 1 mshome mshome 21 2010-06-05 21:28 hoge.txt

vm-ubu01% ln hoge.txt hoge.hl  # ハードリンク作成
vm-ubu01% ls -l              
合計 8
-rw-r--r-- 2 mshome mshome 21 2010-06-05 21:28 hoge.hl
-rw-r--r-- 2 mshome mshome 21 2010-06-05 21:28 hoge.txt

vm-ubu01% ln hoge.txt hoge.hl2 # ハードリンクをもう一つ作成

vm-ubu01% ls -l # ハードリンクを2つ作成したのでリンクカウントが3になっています。
合計 12
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:28 hoge.hl
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:28 hoge.hl2
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:28 hoge.txt

vm-ubu01% touch hoge.txt # 元ファイルのタイムスタンプを更新します。

vm-ubu01% ls -l # ハードリンクファイルもタイムスタンプが更新されています。
合計 12
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.hl
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.hl2
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.txt

vm-ubu01% ln -s hoge.txt hoge.sl # シンボリックリンクを作成します。

vm-ubu01% ls -l 
合計 12
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.hl
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.hl2
lrwxrwxrwx 1 mshome mshome  8 2010-06-05 21:31 hoge.sl -> hoge.txt
-rw-r--r-- 3 mshome mshome 21 2010-06-05 21:31 hoge.txt

# ハードリンク、シンボリックリンクそれぞれ参照できます。
vm-ubu01% more hoge.hl
hogehogehogehogehoge
vm-ubu01% more hoge.hl2
hogehogehogehogehoge
vm-ubu01% more hoge.txt 
hogehogehogehogehoge
vm-ubu01% more hoge.sl 
hogehogehogehogehoge

vm-ubu01% rm hoge.txt # 元ファイルを削除します。

# ハードリンクファイルは参照することができますが、シンボリックリンクファイルは参照を辿ることができません。
vm-ubu01% more hoge.hl 
hogehogehogehogehoge
vm-ubu01% more hoge.hl2
hogehogehogehogehoge
vm-ubu01% more hoge.sl 
hoge.sl: No such file or directory
vm-ubu01% >||
zsh: parse error near `|'
vm-ubu01% ln 参照元ファイル ハードリンクファイル
ln: `参照元ファイル' にアクセス中: No such file or directory
vm-ubu01% ||<
zsh: parse error near `||'
vm-ubu01%