5-Minute Coffee Tip #0: How to Create an Alias Command
Or How to Deal with Really Long & Annoying Commands
Table of contents
Since I have been doing a lot of programming in Python lately that I have to create a new virtual environments for, I have to enter in a really long command and then I need to activate it with another really long command.
It’s becoming quite tedious.
So I dug around in my bash notes and discovered I had written something down about creating your own commands called “aliases".
So for this tutorial, I'm gonna show you how to create an alias command, especially if you have a Mac.
Check for .zshrc
file
First, you need to see if you already have a hidden file named, .zshrc
.
Open your Terminal and make sure that you are in your home directory, e.g. ~/(home user)
.
Then you need to type this command to see all the files and folders in your home directory:
ls -a
The ls
command with the -a
option will list out all the files and folders that exist in your home directory, including all the hidden ones.
Look to see if you have a .zshrc
file in this list.
If you do not, you need to create it by running this command:
touch ~/.zshrc
Then run ls -a
again and look to see if you successfully added it.
Edit it in Nano
Now it’s time to edit it in Nano!
Type this command to open the file in Nano:
nano .zshrc
In my example, I want to just type my own custom command, new_venv
, so that all I need to do is type this in Terminal for whatever project I want to have Python virtual environment for.
Currently to run the command to create a new Python virtual environment for every new project, I have to constantly type this into Terminal: python3 -m venv venv
.
I am going to do the same for activating a virtual environment, the command for this is: source venv/bin/activate
.
Here’s how I have my the .zshrc
file is set up, please make sure that the file contents ends with fi
or you will get an error message when you try to load it into your shell:
alias new_venv="python3 -m venv venv"
alias activate="source venv/bin/activate"
fi
Also make sure you have no extra spaces or newlines.
Exit and save your .zshrc
file.
Load .zshrc
file into shell
Now you need to load the file in the shell by running this command in the Terminal:
source .zshrc
Relaunch your Terminal window or open a new one, head over to a Python project folder within Terminal and test out your new, shiny alias command.
Type in your new command:
new_venv
And it should run the command (that was stored under the alias that you added to your .zshrc
file) to create a new virtual environment in your project folder!
Too easy - now take a congratulatory sip of coffee. 😌☕️