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 cd 指令進階用法:絕對/相對路徑、特殊符號與符號連結處理

編輯:Linux 教學

cd(change directory)是 Linux 終端機中使用頻率最高的指令,看似簡單卻暗藏許多提效細節。本文系統整理路徑表示法、特殊符號速記、符號連結穿透行為與環境變數跳轉技巧,助您在目錄樹中如魚得水。

基本語法

cd [目錄路徑]

無參數時自動切換至 $HOME(通常為 /home/使用者名 或 /root)。

路徑表示法速查

符號/寫法含義範例
/根目錄cd /
~當前使用者家目錄($HOME)cd ~/projects
~user指定使用者家目錄cd ~admin
.目前目錄cp /etc/nginx/nginx.conf .
..上一層目錄cd ../.. 往上兩層
-上一次工作目錄($OLDPWD)cd - 來回切換

參數選項

參數行為差異
-L(預設)遇到符號連結,進入連結所指向的實體目標目錄
-P遇到符號連結,保持在符號連結路徑下(pwd 顯示連結路徑)

符號連結行為實測

$ mkdir -p /tmp/real_dir
$ ln -s /tmp/real_dir /tmp/link_dir

# 預設 -L 行為
$ cd -L /tmp/link_dir
$ pwd
/tmp/real_dir          # 顯示實體路徑

# -P 行為
$ cd -P /tmp/link_dir
$ pwd
/tmp/link_dir          # 保持符號連結路徑

高效跳轉技巧

1. 善用 cd - 雙目錄來回

$ cd /etc/nginx/conf.d
$ cd /var/log/nginx
$ cd -        # 回到 /etc/nginx/conf.d
$ cd -        # 再回 /var/log/nginx

2. 組合大括號展開快速建立並進入多層目錄

mkdir -p project/{src,test,doc}/{main,module}
cd project/src/main

3. 變數替換動態構建路徑

BASE=/opt/apps
VER=2.3.1
cd "$BASE/myapp-$VER/config"

4. 子 Shell 隔離目錄切換不影響父 Shell

(cd /tmp && ls)  # 結束後仍在原目錄

常見問題排查

  • 權限拒絕:目錄需具備 x(進入)權限,chmod +x dir。
  • 參數過多:cd 僅接受單一目錄參數,多參數會報錯。
  • 特殊字元檔名:空格、括號、萬用字元需加引號或跳脫:cd "My Documents" 或 cd My\ Documents。

進階:自動補全與歷史搜尋

  • Tab:路徑自動補全(雙擊列出候選)
  • Ctrl+R:歷史指令反向搜尋,輸入 cd 關鍵字快速調取過往路徑
  • cd !$:重用上一條指令的最後一個參數(如 mkdir /a/b/c 後 cd !$ 直接進入)

熟練掌握 cd 的各種路徑表示與跳轉技巧,是終端機操作流暢度的基石。建議將常用專案路徑加入 CDPATH 環境變數(export CDPATH=.:~:/opt/projects),即可在任意位置直接 cd 專案名 直達目標目錄。

Copyright © Windows教程網 All Rights Reserved