眾所周知,如果沒有 cd 命令,我們無法 Linux 中切換目錄。這個沒錯,但我們有一個名為 shopt的 Linux 內建命令能幫助我們解決這個問題。
shopt[1] 是一個 shell 內建命令,用於設定和取消設定各種 bash shell 選項,由於它已安裝,因此我們不需要再次安裝它。
是的,我們可以在啟用此選項後,可以不使用 cd 命令切換目錄。
我們將在本文中向你展示如何操作。這是一個小的調整,但對於那些從 Windows 遷移到 Linux 的新手來說非常有用。
這對 Linux 管理員沒用,因為我們不會在沒有 cd 命令的情況下切換到該目錄,因為我們對此有經驗。
如果你嘗試在沒有 cd 命令的情況下切換 Linux 的目錄/檔案夾,你將看到以下錯誤訊息。這在 Linux 中很常見。
-
$ Documents/ -
bash: Documents/: Is a directory
為此,我們需要在使用者 .bashrc 中追加以下值。
什麼是 .bashrc ?
.bashrc 是一個 shell 指令碼,每次使用者以互動樣式開啟新 shell 時都會執行該指令碼。
你可以在該檔案中新增要在命令提示符下輸入的任何命令。
.bashrc 檔案本身包含終端會話的一系列配置。包括設定和啟用:著色、補全,shell 歷史,命令別名等。
-
$ vi ~/.bashrc
加入這一行:
-
shopt -s autocd
執行以下命令使更改生效。
-
$ source ~/.bashrc
我們已完成所有配置。簡單地對此進行測試以確認這是否有效。
-
$ Documents/ -
cd -- Documents/ -
-
$ daygeek/ -
cd -- daygeek/ -
-
$ /home/daygeek/Documents/daygeek -
cd -- /home/daygeek/Documents/daygeek -
-
$ pwd -
/home/daygeek/Documents/daygeek

是的,它正如預期的那樣正常工作。
而且,它在 fish shell 中工作正常,而無需對 .bashrc 進行任何更改。

如果要暫時執行此操作,請使用以下命令(設定或取消設定)。重啟系統時,它將消失。
-
# shopt -s autocd -
-
# shopt | grep autocd -
autocd on -
-
# shopt -u autocd -
-
# shopt | grep autocd -
autocd off
shopt 命令提供了許多其他選項,如果要驗證這些選項,請執行以下命令。
-
$ shopt -
autocd on -
assoc_expand_once off -
cdable_vars off -
cdspell on -
checkhash off -
checkjobs off -
checkwinsize on -
cmdhist on -
compat31 off -
compat32 off -
compat40 off -
compat41 off -
compat42 off -
compat43 off -
compat44 off -
complete_fullquote on -
direxpand off -
dirspell off -
dotglob off -
execfail off -
expand_aliases on -
extdebug off -
extglob off -
extquote on -
failglob off -
force_fignore on -
globasciiranges on -
globstar off -
gnu_errfmt off -
histappend on -
histreedit off -
histverify off -
hostcomplete on -
huponexit off -
inherit_errexit off -
interactive_comments on -
lastpipe off -
lithist off -
localvar_inherit off -
localvar_unset off -
login_shell off -
mailwarn off -
no_empty_cmd_completion off -
nocaseglob off -
nocasematch off -
nullglob off -
progcomp on -
progcomp_alias off -
promptvars on -
restricted_shell off -
shift_verbose off -
sourcepath on -
xpg_echo off
此外,我找到了一些其他程式,它們可以幫助我們在 Linux 中比 cd 命令更快地切換目錄。
它們是 pushd、popd、up shell 指令碼和 bd 工具。我們將在接下來的文章中介紹這些主題。
知識星球