Linux dirs stack - pushd and popd
pushd, popd, and dirs are shell builtins which allow you manipulate the directory stack. This can be used to change directories but return to the directory from which you came.
The directory stack is a list of recently-visited directories. The pushd builtin adds directories to the stack as it changes the current directory, and the popd builtin removes specified directories from the stack and changes the current directory to the directory removed. The dirs builtin displays the contents of the directory stack. The current directory is always the "top" of the directory stack.
The contents of the directory stack are also visible as the value of the DIRSTACK shell variable.
FILO first-in-dir last-out-dir flow
pushd navigate/ #cd to navigate/ dir and adds absolute path to navigate/ dir to directory stack dirs -v #manages dir stack, -v lists the stack verbosely popd #consumes first pushed/added directory from stack
Demonstrate
mkdir -p ./navigate/dir{1..3}
piotr@ubuntu /tmp $ pushd navigate/ #cd and added to left/top of the stack
/tmp/navigate /tmp
piotr@ubuntu /tmp/navigate $ pushd dir1/ #cd and added to left/top of the stack
/tmp/navigate/dir1 /tmp/navigate /tmp
piotr@ubuntu /tmp/navigate/dir1 $ pushd ../dir2/ #cd and added to left/top of the stack
/tmp/navigate/dir2 /tmp/navigate/dir1 /tmp/navigate /tmp
piotr@ubuntu /tmp/navigate/dir2 $ pushd ../dir3/ #cd and added to left/top of the stack
/tmp/navigate/dir3 /tmp/navigate/dir2 /tmp/navigate/dir1 /tmp/navigate /tmp
piotr@ubuntu /tmp/navigate/dir3 $ dirs -v #show the directory stack
0 /tmp/navigate/dir3
1 /tmp/navigate/dir2
2 /tmp/navigate/dir1
3 /tmp/navigate
4 /tmp
piotr@ubuntu /tmp/navigate/dir3 $ popd #cd to last added /or left /or with the index [1]
/tmp/navigate/dir2 /tmp/navigate/dir1 /tmp/navigate /tmp
piotr@ubuntu /tmp/navigate/dir2 $ popd
/tmp/navigate/dir1 /tmp/navigate /tmp
piotr@ubuntu /tmp/navigate/dir1 $ popd
/tmp/navigate /tmp
piotr@ubuntu /tmp/navigate $ popd
/tmp
piotr@ubuntu /tmp $ popd
bash: popd: directory stack empty
Additional options and switches
dirs -c #clears out the directory stack cd ~2 #cd taking advantage using directory stack, here cd to index.2 dir in the stack #just remember index.0 always changes, to preserve the order always pushd dummy dir /or current dir .