Bash Tips: Custom Commands
Create shortcuts for common operations
February 25, 2023
A Short Introduction to Bash
The terminal is a text-based interface used to interact with a computer. Bash is the language of the terminal. Bash comes with a large standard library of utility functions stored as files, which get executed by typing in their filenames. The basic operations of the terminal are to read, write, and execute files.
Bash scripts can quickly grow in complexity. Commands are grouped together by functions, and communicate with each other using pipes. I consider bash to have the most value when kept simple, automating common processes that would otherwise be done manually.
Getting Started
Bash configurations are stored in a file named ~/.bash_profile (among others). This file runs every time a terminal window opens and is used to store settings that customize the bash environment. I mostly use it to save aliases and custom functions. Here are a few example uses for such custom commands.
Navigate to a commonly used directory
Oftentimes my work is located in a specific folder that is not the home directory. Navigating to that directory every time I open the terminal can feel tiresome. To allieve this inconvenience I make a short alias that automatically navigates to a specific folder.
alias xy="cd ~/path/to/a/folder";
Use a single alias to run a group of commands
Sets of commands often run together. For example, committing to a git repo usually involves three separate commands. Using an alias, the three can be grouped into a single command*.
alias gitsave="git add --all; git commit -m 'save'; git push;";
* This may or may not be advisable.
Create a custom command that accepts parameters
Extending the above example with git, it might be good practice to use a more descriptive commit message. Aliases don't accept parameters, so we'll need to make a function.
function gitsave() {
commit_message=${1:-save}; # "save" will be the default message
git add --all;
git commit -m "${commit_message}";
git push;
}