DEV Community


Fun with BASH Pt: 2 Aliases

sirclesam profile image Sirclesam Updated on ・2 min read

Pt 1:

This one will be short, which makes sense in context.

Another way to save precious keystroked when working in the terminal is to use bash aliases. My main use for this is to get to project directories that I access frequently.

If you read my previous post about writing bash scripts you may have thought to try something like this, but realized after the script executes that you're still in the same directory. This is because in .sh scripts cd just changes the directory in the context of the script and not your active shell, luckily alias can help with this.

Once again we're going to be editing our bash profile file in our home dir. For most BASH shells on linux this will be ~/.bashrc however because apple with the stock OSX terminal it is ~/.bash_profile.

For a while, I've been doing daily hack-hours to practice algorithm solving, pulling from a daily updated repo that has new problems in it every day. In order to interact with the scripts I need to be in their directory which means typing:

cd hack-hour/challenges/

which even with tab correction still equals 5 keystrokes every morning. Ain't nobody got time for that!

open up your bash profile and insert the following:

alias hh="cd ~/hack-hour/challenges"

Go open a new terminal (has to be new, remember the profile settings get added when a terminal is opened) and try it!


Originally that was going to be all for this article, but I learned a new BASH trick that I can rope back into this so you get that too.

I just learned you can cd - to go back the previous directory you were in, pretty neat but got me thinking about some alias work I'd done in college when we lived in the terminal.

pushd is a less well-known sibling of cd. It does the same thing but as its name might have suggested it does a push, and this is on to a directory stack. The benefit of this is you can do a popd to traverse backwards through the stack.

Another thing to note about aliases, that this demonstrates, is they get executed before anything on your PATH environment variable, so if you add this to your profile:

alias cd="pushd"

now anytime cd is used it will call pushd instead and you can utilize popd to go back in your directory history, if cd - doesn't get the job done!

That's it for now,

Discussion (0)

Editor guide