FUN WITH LINUX

Using pushd/popd

23 July 2016

Most linux-users know $OLDPWD. It’s an environment variable to get the recently used directory. Sometimes it would be nice to remember more visited directories. In such cases pushd and popd would be a good choice..

Most common shells do have a directory stack. By looking in the man-page of bash I found the following description of the DIRSTACK:

An array variable (see Arrays below) containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.

If we call pushd we can change the directory and save the current directory to the directory stack:

dr@tardis:~$ pushd /tmp
/tmp ~
dr@tardis:/tmp$ echo $DIRSTACK
/tmp
dr@tardis:/tmp$ pushd /home
/home /tmp ~
dr@tardis:/home$ pushd /opt    
/opt /home /tmp ~

So now I am at /opt and have the following directories in my DIRSTACK: /opt /home /tmp ~ Now I will walk back all the way:

dr@tardis:/opt$ popd 
/home /tmp ~
dr@tardis:/home$ popd 
/tmp ~
dr@tardis:/tmp$ popd
~
dr@tardis:~$ 
[ Linux  Sysadmin  Bash  Tricks  Shell  Zsh  ]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 Unported License.

Copyright 2015-present Hoti