Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux ln 指令完整操作指南:硬連結與符號連結實戰詳解

編輯:關於 Linux

ln 是 Linux 檔案系統管理的核心指令,用於建立「硬連結」與「符號連結(軟連結)」。兩者機制迥異:硬連結共享 inode,符號連結僅記錄路徑字串。本文透過實驗驗證兩者差異,並說明實務應用場景與陷阱。

基本語法

ln [選項] 目標檔案 連結名稱
ln [選項] 目標檔案... 目標目錄
選項功能
-s, --symbolic建立符號連結(預設為硬連結)
-f, --force移除既有同名檔案後再建立
-i, --interactive覆蓋前詢問
-n, --no-dereference目標為符號連結目錄時,視為一般檔案處理
-v, --verbose顯示處理過程

實驗 1:建立符號連結

touch /tmp/source_file
ln -s /tmp/source_file /tmp/symlink
ls -lhi /tmp/source_file /tmp/symlink

輸出:

3441 -rw-r--r-- 1 user user 0 Mar 15 10:00 /tmp/source_file
3647 lrwxrwxrwx 1 user user 17 Mar 15 10:01 /tmp/symlink -> /tmp/source_file

觀察重點:

  • Inode 不同(3441 vs 3647),符號連結佔用獨立 inode。
  • 權限 lrwxrwxrwx,l 表符號連結,權限固定 777(實際存取受限於目標檔案)。
  • 大小 17 bytes = 目標路徑字串長度 /tmp/source_file。

實驗 2:刪除符號連結 vs 刪除目標檔案

echo "link test" > /tmp/source_file
cat /tmp/symlink          # 輸出: link test
rm /tmp/symlink
cat /tmp/source_file      # 輸出: link test (目標檔案未受影響)

ln -s /tmp/source_file /tmp/symlink
rm /tmp/source_file
cat /tmp/symlink          # 錯誤: No such file or directory
ls -l /tmp/symlink        # 顯示斷連結 (紅色標示)
# 此時 symlink 成為「懸空連結」

結論: 刪除連結不影響目標;刪除目標導致連結失效(懸空連結)。

實驗 3:建立硬連結

touch /tmp/hard_source
ln /tmp/hard_source /tmp/hardlink
ls -lhi /tmp/hard_source /tmp/hardlink

輸出:

4001 -rw-r--r-- 2 user user 0 Mar 15 10:05 /tmp/hard_source
4001 -rw-r--r-- 2 user user 0 Mar 15 10:05 /tmp/hardlink

觀察重點:

  • Inode 相同 (4001),連結計數從 1 變 2。
  • 權限、大小、時間戳完全一致(因為是同一個檔案)。
  • 硬連結無法跨檔案系統(Inode 僅在單一檔案系統內唯一)。
  • 硬連結不能針對目錄(除非 root 使用 -d,極不建議,破壞檔案系統結構)。

硬連結 vs 符號連結 比較表

特性硬連結符號連結
Inode共享獨立
跨檔案系統不可可
連結目錄不可可
目標不存在不可能(建立時必須存在)可(懸空連結)
刪除目標檔案資料保留(連結計數-1,歸零才釋放區塊)連結失效
權限顯示同目標lrwxrwxrwx
相對/絕對路徑無路徑概念支援相對路徑(建議使用)

實務應用場景

1. 版本管理與無縫切換(符號連結)

/opt/app/v1.0  # 實際安裝目錄
/opt/app/v1.1
/opt/app/current -> /opt/app/v1.1  # 部署新版後切換連結
# systemd/service 腳本皆指向 /opt/app/current

2. 共用設定檔/資料目錄(符號連結)

ln -s /mnt/shared/config /etc/myapp/config
ln -s /data/logs /var/log/myapp

3. 節省空間的備份/快照(硬連結)

# rsync --link-dest=/backup/yesterday /src /backup/today
# 未變更檔案僅建立硬連結,佔用極小額外空間

4. 確保檔案不被意外刪除(硬連結)

ln /important/file /root/protect/file
# 即使原路徑被刪除,/root/protect/file 仍保留資料

常見陷阱與最佳實踐

  • 相對路徑符號連結:ln -s ../config/app.conf /etc/app.conf 遷移目錄樹時不失效。
  • 避免循環連結:ln -s a b; ln -s b a 導致遞迴存取爆炸。
  • 備份工具行為:tar 預設解析符號連結(存目標內容),cp -a 保留連結屬性,rsync -l 保留符號連結,-H 保留硬連結結構。
  • find 查找:find / -type l 找符號連結,find / -links +1 找硬連結檔案。

總結

掌握 ln 核心在於理解 Inode 機制:硬連結 = 同一 Inode 多個目錄項;符號連結 = 含路徑字串的特殊檔案。選擇原則:跨檔案系統、連結目錄、需懸空特性 → 符號連結;同檔案系統、追求空間效率、防誤刪 → 硬連結。

Copyright © Windows教程網 All Rights Reserved