我需要回到bash脚本内的父目录。我知道该目录将位于我当前的路径中,但是现在脚本可以将我的位置扩展到2到5级深。该脚本是克隆的git repo的一部分,因此我无法从用户的根目录开始,因为我不知道他们将其克隆到何处或下降了几级。
假设我的文件结构如下:
User's dir structure
repo
foo
bar
baz
a
fizz
b
bang
c
我需要回到foo
,但我不知道自己是在a
,b
还是c
,甚至是bar
中。
我目前的想法是将其削减并削减,因此我只有*/foo/
,然后是cd,但这真的是最有效的方法吗?
将变量设置到原始目录。
origdir=$(pwd)
# code that jumps around...
cd "$origdir"
您也可以使用目录堆栈。
pushd -n "$PWD" # Store the current working directory on the stack
...
popd # Return to the directory on top of the stack
如果您不需要在pushd
和popd
之间进行很多目录更改,因为您只需写就可以,这特别有用
pushd some/directory/path # Puts current working dir on the stack, then cd's to the argument
...
popd
(即使有更改,您仍然可以使用pushd
。pushd foo
等效于pushd -n "$PWD"; cd foo
。]