Bash
腳本來記住目錄並始終 cd 到它而不是根目錄
如何編寫腳本以更改到給定目錄但還要記住它,以便當您執行 cd 時它總是更改到該目錄?
#!/bin/bash setdir() { cd $1 # remember the directory we are changing to here so whenever we do cd we go back to this set dir } setdir "$1"
像下面這樣的東西應該可以工作:
setdir() { cd "$1" export SETDIR_DEFAULT="$1" } my_cd() { cd "${1-${SETDIR_DEFAULT-$HOME}}" }
請注意,這些是函式,而不是單獨的腳本。您不能從單獨的腳本中執行此操作,因為它無法影響呼叫它的父 shell。
如果您真的想覆蓋
cd
(請不要這樣做),請替換cd
為builtin cd
.
我知道答案可能有點晚了,但你可能會喜歡
CDPATH
vaiable 的想法。它允許cd
從任何地方引用此變數中的目錄內容。這是一個例子:$ mkdir -p test/{1,2,3} $ cd test/ $ mkdir 1/{a,b,c} $ export CDPATH=/tmp/test/1 $ ls 1 2 3 $ cd a $ pwd /tmp/test/1/a $ cd ~ $ cd b $ pwd /tmp/test/1/b
更多詳情來自
man
:CDPATH A <colon>-separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory, as described in the DESCRIPTION. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string.