Bash cd back to previous directory and keeping a history

Bash cd back to previous directory and keeping a history

change working directory back to a previous location using several different methods. Use specific commands to keep a history of directories visited. Examples made in Ubuntu linux.


CD back to your previous working directory


Probably the cleanest option using only the 'cd' command is to use:


cd -


This command will set your current directory to the one from where you just came, it only holds the history of the very last CD. Running this command multiple times will take you back and forth from your first directory to the second and back to the first, etc. This command will also stream the directory it is relocating you to into stdout.


root@testing:~# cd /tmp
root@testing:/tmp# cd /home
root@testing:/home# cd -
/tmp
root@testing:/tmp# cd -
/home
root@testing:/home# cd -
/tmp


Another way to accomplish the exact same thing would be to use the $OLDPWD system variable which is set when switching directories (this is what 'cd -' actually uses behind the scenes). If you echo this variable it will output your previous directory:


root@testing:~# cd /tmp
root@testing:~# cd /home
root@testing:~# echo $OLDPWD
/tmp


So you can quite easily use this to change back to your previous directory


root@testing:~# cd $OLDPWD


Keeping a history of visited directories using pushd and popd


If you're willing to make use of commands other than cd, you can make use of the built-in commands pushd and popd


pushd <your directory> changes your directory to the given path just like cd does, but also pushes your previous and current directory to a directory history stack which can be accessed with popd. It also streams the current directory history stack to stdout.

root@testing:~# pushd /tmp
/tmp ~
root@testing:~# pushd /home
/home /tmp ~
root@testing:~# pushd /var
/var /home /tmp ~


You can then use popd to return to previous directories, in the order that you visited them. It will output the directory history stack to stdout AFTER popping the directory at the head of the stack and changing your directory. If there are no more records in the directory history stack it will output the error '-bash: popd: directory stack empty' to stderr


root@testing:/var# popd
/home /tmp ~
root@testing:/home# popd
/tmp ~
root@testing:/tmp# popd
~
root@testing:~# popd
-bash: popd: directory stack empty 


If you have any questions or would like to add anything to this tutorial, feel free to leave a comment below!


Christopher Thornton@Instructobit 4 years ago
or