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 dirs 指令詳解:目錄堆疊操作與快速切換技巧

編輯:Linux 教學

dirs 是 Bash 內建指令,用於顯示目錄堆疊(Directory Stack)內容。它始終將目前工作目錄作為堆疊底部(索引 0),其後依序列出 pushd 加入的目錄。掌握 dirs 搭配 pushd/popd,能在多專案、多層級目錄間實現鍵盤級的極速跳轉,告別冗長的 cd ../../../path。

語法格式

dirs [+/-n] [-clpv]

常用參數

+N-N
參數功能說明
-c清空目錄堆疊所有記錄
-l以完整絕對路徑顯示(不縮寫 ~)
-p每行顯示一個目錄
-v每行顯示一個目錄並附加索引編號(0 為目前目錄)
顯示從左至右第 N 個目錄(0 起算)
顯示從右至左第 N 個目錄(0 起算)

實戰範例

1. 檢視完整堆疊內容(帶索引)

$ dirs -v
 0  /home/user/projectA
 1  /var/log/nginx
 2  /etc/nginx/conf.d
 3  /home/user/scripts

2. 快速切換至堆疊指定層級

# 切換到索引 2 的目錄(/etc/nginx/conf.d)
cd "$(dirs -l +2)"

# 或搭配 pushd 直接旋轉堆疊
pushd +2

3. 清空堆疊重新開始

dirs -c

進階工作流:目錄書籤系統

在 ~/.bashrc 定義快捷函數:

# 將常用路徑推入堆疊並記憶
mark() { pushd "$1" >/dev/null; dirs -v; }
# 列出書籤
marks() { dirs -v; }
# 跳轉至書籤編號
jump() { cd "$(dirs -l +$1)"; }

使用方式:

mark /etc/nginx/conf.d
mark /var/log/nginx
marks
# 輸出:
# 0  /home/user
# 1  /etc/nginx/conf.d
# 2  /var/log/nginx
jump 1  # 直接進入 /etc/nginx/conf.d

關鍵差異:dirs vs pushd vs popd

  • dirs:唯讀檢視,不改變堆疊與目前目錄
  • pushd dir:將 dir 壓入堆疊頂端並 cd 過去
  • popd:彈出堆疊頂端目錄並 cd 回新頂端

適用場景

  • 同時維護多個專案目錄(原始碼、日誌、配置、部署腳本)
  • 深層目錄結構下的來回切換
  • 臨時進入系統目錄排查問題,需快速返回原工作目錄

善用目錄堆疊,能將終端機操作效率提升 30% 以上,是 Linux 進階使用者的必備肌肉記憶。

Copyright © Windows教程網 All Rights Reserved