Linux dirs stack - pushd and popd

From Ever changing code
Revision as of 16:51, 13 May 2019 by Pio2pio (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.

  • pushd add directory to the stack as it changes the current directory, and
  • popd removes specified directories from the stack and changes the current directory to the directory removed.
  • dirs 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


Navigate using cd, it does not remove a dir from the stack. cd takes 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.

dirs -v
 0  /tmp/navigate/dir2
 1  /tmp/navigate/dir3
 2  /tmp/navigate
 3  /tmp
cd ~2   #will cd -> /tmp/navigate, not removing the directory entry on the stack


Additional options and switches

dirs -c #clears out the directory stack