Bash

腳本來記住目錄並始終 cd 到它而不是根目錄

  • April 4, 2019

如何編寫腳本以更改到給定目錄但還要記住它,以便當您執行 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(請不要這樣做),請替換cdbuiltin cd.

我知道答案可能有點晚了,但你可能會喜歡CDPATHvaiable 的想法。它允許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.

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