1. 程式人生 > >硬核bash-cd命令的這六個用法都會嗎?

硬核bash-cd命令的這六個用法都會嗎?

# cd cd [-L|[-P [-e]]] [-@] [directory] ### 1. 切換當前目錄,如果不帶引數,會進入到$HOME 所在目錄 ```bash # 下面三個命令效果一樣的 cd pwd cd ~ pwd cd $HOME pwd # 再來幾個其他的 cd ~- # = cd - 或者 cd $OLDPWD cd ~+ # = cd . 或者 cd $PWD ``` ### 2. 注意如果有$CDPATH這個自帶變數有值的話,會優先從CDPATH的值的目錄下尋找目錄,CDPATH支援設定多個目錄,使用:分隔,不過一般也不會用這個,結果太奇怪了 ```bash # 最後進入了/tmp/test1/test2而不是當前目錄(/tmp)下的test2 mkdir -p /tmp/test1/test2 mkdir -p /tmp/test2 cd /tmp CDPATH=/tmp/test1 pwd #/tmp cd test2 pwd #/tmp/test1/test2 ``` ### 3. -L 和 -P 是相對於符號連結路徑時會有所區別,預設或者加上-L引數,會進入到符號連結的路徑,加上-P 進入的就是真實路徑. ```bash # cd -P /root/test3 顯示的是真實的路徑 mkdir -p /tmp/test1/test2 ln -s /tmp/test1/test2 /root/test3 cd /root/test3 pwd cd -L /root/test3 pwd cd -P /root/test3 pwd ``` ### 4. .. 代表上一級目錄,如果是在根目錄,返回的還是根目錄 ```bash # 最後返回的還是根目錄/ mkdir -p /tmp/test1/test2 cd /tmp/test1/test2 pwd cd .. pwd cd ../../../../../ pwd ``` ### 5. cd -P -e 下面是bash官方原文,目前只發現一種使用情況 當前所在目錄被刪除了,執行cd . 控制檯有報錯,但是返回的狀態還是0正常,而如果執行cd -P -e . 返回的狀態則是1異常 If the -e option is supplied with -P and the current working directory cannot be successfully determined after a successful directory change, cd will return an unsuccessful status. ```bash ## $? 上一條命令的返回值 ## !$ 上一條命令的最後一個引數 [root@master tmp]# mkdir -p /tmp/test1/test2/test3 [root@master tmp]# cd !$ cd /tmp/test1/test2/test3 [root@master test3]# pwd /tmp/test1/test2/test3 [root@master test3]# rm -rf /tmp/test1/test2/test3 [root@master test3]# pwd /tmp/test1/test2/test3 [root@master test3]# cd . cd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory [root@master .]# echo $? 0 [root@master .]# pwd /tmp/test1/test2/test3/. [root@master .]# cd -P -e . cd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory [root@master ]# echo $? 1 ``` ### 6. cd - 返回上一個工作目錄,也就是$OLDPWD中保持的路徑, cd -- -d ,進入-d 目錄,兩個- 使後面的-當做引數而非選項 ```bash [root@master tmp]# pwd /tmp [root@master tmp]# mkdir -p /tmp/test1 [root@master tmp]# cd test1 [root@master test1]# pwd /tmp/test1 [root@master test1]# cd - /tmp [root@master tmp]# mkdir -- -d [root@master tmp]# cd -- -d [root@master -d]# pwd /tmp/-d ``` ### 0. cd -@ 這個需要在支援的系統上生效,目前還沒不知道用法,歡迎