Linux中軟鏈接與硬鏈接詳細解讀
1.測試環境模擬
2.軟鏈接特性
3.硬鏈接特性
4.總結
1.測試環境模擬
1 2 3 4 5 6 7 8 9 10 11 12 13 | [root@localhost home]# mkdir test 創建測試文件夾 [root@localhost home]# cd test/ 進入測試文件夾 [root@localhost test]# touch link 創建原文件link [root@localhost test]# echo "my name is link">>link 寫入內容到原文件link [root@localhost test]# cat link 查看原文件內容 my name is link [root@localhost test]# ln -s link softlink 創建軟鏈接 [root@localhost test]# ln link hardlink 創建硬鏈接 [root@localhost test]# ll total 8 -rw-r--r--. 2 root root 16 Dec 8 18:21 hardlink 硬鏈接 -rw-r--r--. 2 root root 16 Dec 8 18:21 link 原文件 lrwxrwxrwx. 1 root root 4 Dec 8 18:22 softlink -> link 軟鏈接 |
2.軟鏈接特性
1 2 3 | -rw-r--r--. 2 root root 16 Dec 8 18:21 link 原文件
lrwxrwxrwx. 1 root root 4 Dec 8 18:22 softlink -> link 軟鏈接 |
對比差別是不是發現有幾點不同?
1.原文件inode為2軟鏈接為1
2.權限不同
3.文件大小不同
4.軟鏈接後面有個指向link的標誌
1 2 | [root@localhost test]# cat softlink my name is link |
軟鏈接內容一樣。
1 2 3 4 | [root@localhost test]# rm softlink rm: remove symbolic link ‘softlink’? y [root@localhost test]# cat link my name is link |
刪除軟鏈接原文件是正常的
1 2 3 4 | [root@localhost test]# rm link rm: remove regular file ‘link’? y [root@localhost test]# cat softlink cat: softlink: No such file or directory |
刪除原文件軟鏈接找不到文件了,綜上證明軟鏈接就是個快捷方式而已!!!
如果我把軟鏈接改名稱會發生什麽?
1 2 3 4 5 6 7 | [root@localhost test]# mv softlink testsoftlink [root@localhost test]# ll total 8 -rw-r--r--. 1 root root 16 Dec 8 18:36 link lrwxrwxrwx. 1 root root 4 Dec 8 18:34 testsoftlink -> link [root@localhost test]# cat testsoftlink my name is link |
實驗證明改名並沒有什麽卵用,打開軟鏈接照樣可以看到內容,為什麽?
因為linux識別一個文件不看名稱,看inode值!!!
也就是說inode值相同文件內容一樣。
那麽文件可以創建軟鏈接,目錄可以嗎?
1 2 3 4 5 | [root@localhost test]# mkdir wj [root@localhost test]# ln -s wj softwj [root@localhost test]# ll lrwxrwxrwx. 1 root root 2 Dec 8 18:54 softwj -> wj drwxr-xr-x. 2 root root 6 Dec 8 18:54 wj |
目錄可以創建軟鏈接
3.硬鏈接特性
1 2 3 4 5 6 | [root@localhost test]# ll total 8 -rw-r--r--. 2 root root 16 Dec 8 18:36 hardlink -rw-r--r--. 2 root root 16 Dec 8 18:36 link [root@localhost test]# cat hardlink my name is link |
觀察得出硬鏈接就是個原文件的備份
1 2 3 4 | [root@localhost test]# rm link rm: remove regular file ‘link’? y [root@localhost test]# cat hardlink my name is link |
刪除原文件,硬鏈接是可以看到內容的,so。這就是與軟鏈接的不同之處之一。
那麽硬鏈接是否可以像軟鏈接一樣創建目錄鏈接呢?
1 2 3 | [root@localhost test]# mkdir cs [root@localhost test]# ln cs hardcs ln: ‘cs’: hard link not allowed for directory |
不可以的。為什麽呢?
因為那個唯一值!如果目錄inode一樣會怎麽樣?
在訪問軟鏈接的時候通過軟鏈接直接的跳轉到原文件,這樣就訪問了內容
在訪問軟鏈接目錄的時候通過遍歷目錄內容也可以找到,就算文件夾裏面inode值有一樣的循環了,linux可以在8個循環內終結。
但是
如果我們的硬鏈接訪問了,其實原文件變不變與它已經沒有關系了
我們的硬鏈接如果有硬鏈接目錄,那麽遍歷的時候遇到inode值一樣的目錄裏面的內容,全部遍歷一遍,環路至少在目錄的linux系統中終結不了,所以硬鏈接目錄是不能創建滴!!!
4.總結
軟鏈接類似快捷方式,原文件內容變了軟鏈接的也會變,影響文件的不是名稱而是inode值,軟鏈接是可以創建軟鏈接目錄的。
硬鏈接類似備份,原文件內容變化不影響硬鏈接,所以通常在工作用作為快照使用,硬鏈接沒有硬鏈接目錄。
Linux中軟鏈接與硬鏈接詳細解讀