Linux Command Line — A Better cd Command

Al Williams
For Linux Users
Published in
5 min readJul 30, 2020

--

Type less, do more

If you use Bash or a similar shell, you doubtlessly use the cd command regularly to change directories. I’m always a bit surprised that many people don’t know one little shortcut, although with just a tiny bit of work, you can make that shortcut very powerful. Stick around and I’ll show you exactly how to make directory navigation more efficient.

The Easy Shortcut

One thing that is built into the cd command is using a dash to switch to the last current directory. For example, suppose you are switching between /tmp/a and /tmp/b:

Note that if you do the command twice, you wind up back where you started. This is often handy if you need to switch to b, do some stuff, switch to a, do some more stuff, then switch back again.

We Can Do Better

However, it is easy to do better than this, if you include a simple script in your ~/.bashrc file. Try copying this file into the end of your ~/.bashrc file. This does a few things. Note at the bottom of the script is a line:

alias cd=cd_func

That’s one way to activate this script. Every time you use cd to change directories, the script will remember a history of where you have been. You can remove or comment out that line…

--

--

Al Williams
For Linux Users

Engineer. Author. Team Leader. Lots of other things. I blog about hardware hacking for Hackaday (www.hackaday.com), but talk about other topics here.