Creating Bash Aliases Quickly from the Terminal
This is a quick little tip on how I add aliases to common commands for use in bash
or zsh
shells.
Table of Contents
The .aliases file and its contents
Create this file, I put it in my home aka ~/
directory, then add source ~/.aliases
to your shell config files (.bashrc
or .zshrc
). Remember to source
your shell config or restart your terminal so you're able to use the alias functions.
# ~/.aliases
alias_file=~/.aliases
alias last_alias="tail -n 1 $alias_file"
create_alias() {
echo alias $1=\"$2\" >> $alias_file
source $alias_file
last_alias
}
delete_last_alias() {
sed -i '$ d' $alias_file
source $alias_file
last_alias
}
# Aliases
create_alias
Running this function in your shell will now append your new alias to the end of your ~/.aliases file, source that file, then echo back the last line so you can make sure syntax is correct.
create_alias alias_name "echo What we're aliasing"
last_alias
Running this alias in your shell will echo back the last line of your ~/.aliases file so you can check the last alias added.
last_alias
delete_last_alias
Running this function in your shell will delete the last line of your ~/.aliases file, source that file, then echo back the last line so you can decide whether you want to delete that alias too.
delete_last_alias