# MAN 手册原文:
pushd [-n] [+n] [-n]
pushd [-n] [dir]
Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the
stack the current working directory. With no arguments, exchanges the top two directories and
returns 0, unless the directory stack is empty. Arguments, if supplied, have the following meanings:
-n Suppresses the normal change of directory when adding directories to the stack, so that only
the stack is manipulated.
+n Rotates the stack so that the nth directory (counting from the left of the list shown by dirs,
starting with zero) is at the top.
-n Rotates the stack so that the nth directory (counting from the right of the list shown by
dirs, starting with zero) is at the top.
dir Adds dir to the directory stack at the top, making it the new current working directory.
If the pushd command is successful, a dirs is performed as well. If the first form is used, pushd
returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the directory
stack is empty, a non-existent directory stack element is specified, or the directory change to the
specified new current directory fails.
----------
# 概要:
pushd 把一个目录dir添加到目录堆栈顶部;或者交换堆栈顺序,是当前工作目录成为新的栈顶。
没有参数时,只是交换两个目录顺序,使得第二个目录成为栈顶,原栈顶目录下移,成功返回0;只有当目录堆栈为空返回非零值。
----------
命令 | 作用 |
dirs | 显示目录栈的内容,即便目录栈为空,它也会显示当前工作目录。 |
pushd | 把当前工作目录压栈,成为栈顶。 |
popd | 将目录弹出目录栈 |
# 操作记录
1)没有把任何目录压入目录栈时,目录栈为空,此时的pushd, popd 命令都是无效的,会出错,只有 dirs 命令能够显示一个目录,但这个目录不在目录栈里面。
2)“pushd $PWD” 把当前工作目录压入栈里面,dirs 命令能够显示两个目录,第一个是栈顶,刚刚压入的目录;而 “popd” 也能够正确执行,是因为它能够弹出栈顶。执行第二次肯定出错。
----------
如果没有使用 pushd $PWD 命令,那么栈顶的目录是临时的,使用 popd 目录会弹出栈顶那个目录,使得当前工作目录切换到序号为1的目录,例如:
再例如:
------
# 指定弹出第 n 个目录条目
终于搞明白了 "pushd +5" 的意思:原来目录栈是一个循环结构,当把序号为5的栈蛇者为栈顶,那么其后面的序号就从0开始,到了栈底再从最前面的目录条目开始,直到遇到刚刚设立的那个栈顶。