How and Why to Make a Bash Alias
One of the most obviously annoying things about the terminal — especially to those of us living in the age of touch and GUIs — is how much you need to type. Typing `ssh email@example.com` is never going to feel as fast as hitting a “connect” button, for example. As such, some people just never really like the terminal. While it’s hardly a solution to all your complaints, BASH (and most other Unix terminals) offer a solution to the issue of typing long commands. They’re called “aliases”. They’re essentially shortcuts to commonly typed things that can be as short as one letter. In the case of that’s video that’s exactly what we’ve done. We aliased (the already pretty short :p) command `clear` to be executable with the letter `c`. Here’s the video:
And the text explanation, if that’s more your speed:
How to Create a Bash Alias That Persists Over Time
Simply creating a BASH alias is pretty simple. It just requires executing a simple command:
alias c="clear". If you run that in your terminal, you’ll have a working alias that means that typing “c” will clear your terminal window. The issue is, once you end that terminal session, that alias will go away. For that reason, you typically actually use a more complex feature of BASH when you’re making aliases. You use the
.bashrc file to store those alias commands and have them rerun each time your terminal restarts. BASH will look for and run both of those files before it opens, so your aliases will always be there.
Here’s how you create persistent aliases in your terminal:
- Open your terminal emulator of choice. I favor iTerm 2 on the Mac. Macs and most Linux distributions come with one called “Terminal”. (I don’t know enough about Windows to be helpful there.)
sudo nano ~/.bashrcin your BASH terminal window. This will open up the Nano text editor, which is my personal favorite for simple editing. You can use others.
sudois likely to be necessary for permission reasons, if it is and you use it, supply the password before going on to the next step.
- In that file, add the line:
alias c=clear. Generally leave the rest of that file in place, you’re just wanting to add a line anywhere you want in the file.
- Save out the file by hitting Ctrl + O (in Nano).
- Quit Nano by hitting Ctrl + X (in Nano).
- Close the terminal window.
- Open a new terminal session, usually by hitting “New window” in your terminal emulator.
- Try out your alias by typing
cand then hitting Enter. You should see your terminal clear.
If the above steps don’t work, you may not have saved your
.bashrc file, or your new session may not be loading it. The second problem is beyond the scope of this Quick Guide, the first just requires you re-do the steps we did. Happy hacking!