push popd and cd -

Posted on Saturday, August 9, 2014


It seems I am learning something new everyday here at my new job.
And it always seems no matter how long you have been doing Unix command line you learn something new you should have known years ago.

This post is about such a thing I feel I should have known a long time ago.


I got an instant message from a fellow employee to the group telling us all to run a simple command line program to fix an issue.   I won't go into the particulars but the one line was several Unix commands separated by a semicolon and it ended with a cd -

This cd - caught my attention I had never seen or used it before.  So I tested it out a bit and googled for it and found http://mylinuxbook.com/20-interesting-and-extremely-helpful-linux-command-line-tricks/ [1]

This article will go over cd - as well as pushd and popd.


So what does cd - do?



> cd -


This will go to the last directory your command line was last at.

As an example


> cd Desktop; ls -alh; cd -


This will change to the Desktop directory and then run another linux command "ls -alh"  then it will return to the previous directory it was at.

Pretty useful

But it has one problem...  what if, throughout your one liner, change the directory several times?  You would have to add a cd - at the end for each time your changed directories…  Or you could use pushd and popd

With pushd and popd I could run the following command line one liner to have the same effect as the example above.


> pushd .; cd Desktop; ls -alh; popd



This works well if you change directories several times

For example


      > pushd .; cd /var/log/; cat wifi.log; cd /home/; ls -alh; popd





References
[1]        20 interesting and extremely helpful Linux command line tricks
                Accessed 08/2014