如何编写一个脚本来更改到给定目录,同时记住它,以便当您执行 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"
答案1
像下面这样的东西应该有效:
setdir() {
cd "$1"
export SETDIR_DEFAULT="$1"
}
my_cd() {
cd "${1-${SETDIR_DEFAULT-$HOME}}"
}
请注意,这些是函数,而不是单独的脚本。您不能从单独的脚本中执行此操作,因为它无法影响调用它的父 shell。
如果你真的想要覆盖cd
(请不要这样做),替换cd
为builtin cd
.
答案2
我知道现在回答可能有点晚了,但您可能会喜欢CDPATH
可用的想法。它允许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.