Bash

是否有一個單行程序允許我創建一個目錄並同時移入它?

  • February 18, 2022

我發現自己重複了很多:

mkdir longtitleproject
cd longtitleproject

有沒有一種方法可以在一行中完成而不重複目錄名稱?我在這裡狂歡。

這是您需要的單線。無需其他配置:

mkdir longtitleproject && cd $_

bash 中的$_變數是上一個命令的最後一個參數。在這種情況下,您剛剛創建的目錄的名稱。如中所述man bash

_         At  shell  startup,  set to the absolute pathname used to invoke
         the shell or shell script being executed as passed in the  envi‐
         ronment  or  argument  list.   Subsequently, expands to the last
         argument to the previous command, after expansion.  Also set  to
         the  full  pathname  used  to  invoke  each command executed and
         placed in the environment exported to that command.  When check‐
         ing  mail,  this  parameter holds the name of the mail file cur‐
         rently being checked."$_" is the last argument of the previous command.

用於cd $_檢索上一個命令的最後一個參數,而不是cd !$因為在 shell 歷史記錄中cd !$給出上一個命令的最後一個參數:

cd ~/
mkdir folder && cd !$

你最終回家(或 ~/ )

cd ~/
mkdir newfolder && cd $_

你最終在 home 下的 newfolder 中!(或 ~/newfolder )

引用自:https://unix.stackexchange.com/questions/9123