Create Custom Terminal Commands (Aliases & Functions)
How to create custom commands?
Sometimes it's really annoying to constantly type git add . then git commit -m "message" . Isn't there a simple way?
Actually, There is. You can create your own command
There is a configuration file in your system that runs every time you start a terminal.
In macOS is :
.zshrcIn Linux is :
.bashrc
This file is responsible for all types of commands in your OS to run properly. So we need to add our custom command directly in those files, but that's not neat. It's better to create a file and provide this file to .zshrc (or .bashrc).
So we wanna make short commands that do the boring stuff like git add and git commit , and other commands like git reset and git clean and git checkout Head to clean our mess. But as you can see, these are too boring, and we need a shortcut for that.
Let's define two commands for both of those processes.
nopeThis command is gonna clear our messcommit <message>This command is going to dogit addandgit commitfor us, and if we provide a message is going to commit those changes with that certain message, and if we don't, it is going to commit those changes with theWIPmessage ("Work in Progress").
Let's first make the file:
touch ~/.custom_command.shThen open the file:
I used VSCode, but you can create and open the file using nano ~/.custom_command
code ~/.custom_command.shNow, let's fill the file with these:
#!/bin/bash
# Alias for git reset
alias nope="git reset --hard && git clean -f -d && git checkout HEAD"
commit (){
commitMessage=$1
if [ -z "$commitMessage" ]; then
commitMessage="WIP"
fi
git add .
git commit -m "$commitMessage"
}Great! As you can see, we've defined an alias for nope cause we just needed to run those commands to reset.
But we've defined a function for commit cause the user (us) may provide an input and maybe not, so we need to handle both situations.
we could use
aliasfor commiting but in that case we couldn't handle the situation that user won't provide the commit message
This is much more flexible.
Alright, we need to open our .zshrc (or .bashrc ) and address this file:
code ~/.zshrcOr:
nano ~/.zshrcAt the end of that file, you have to use source keyword to address the file:
source ~/.custom_command.shSave the file and close it.
Close all terminal windows and reopen them for the changes to take effect.
Done!