Aliases and Functions in Bash: A Complete Guide
What Are Aliases and Functions?
Bash aliases and functions are two powerful mechanisms that allow you to shorten, simplify, and extend the shell’s command-line interface. An alias is a shorthand—a simple replacement for a command or a sequence of commands. For example, typing ll instead of ls -la. A function is a more robust construct that can accept arguments, use variables, include control flow (if, for, while), and return values. While aliases are best for trivial abbreviations, functions are suitable for complex logic.
Both are defined in your shell’s configuration file (~/.bashrc, ~/.bash_profile, or ~/.profile) so that they are available every time you open a terminal. They can also be defined interactively for a single session.
Why Aliases and Functions Matter
In daily development work, you often type the same long commands repeatedly: git status, docker ps -a, ssh -i ~/.ssh/prod_key user@host. Aliases reduce keystrokes and prevent typos. Functions take this further by allowing dynamic behavior—for instance, a function that creates a timestamped backup of a directory or a function that compiles and runs a C program with a single command.
- Productivity: Less typing means faster workflows.
- Consistency: Standardize command usage across a team or project.
- Safety: Add confirmation prompts or validation steps inside functions.
- Portability: Share your custom commands via dotfiles repositories.
How to Use Aliases
Defining a Simple Alias
An alias is defined with the alias builtin command:
alias ll='ls -la'
alias gs='git status'
alias dc='docker-compose'
After sourcing your shell config or running these lines in your terminal, ll becomes an alias for ls -la. Note that the alias definition is a string—you can include quotes, pipes, or multiple commands separated by ;.
Temporary vs Permanent Aliases
Temporary aliases are defined in the current shell session and vanish when you close it. To make an alias permanent, add the alias line to your ~/.bashrc or ~/.bash_aliases file and then run source ~/.bashrc.
# In ~/.bashrc or ~/.bash_aliases
alias myip='curl -s ifconfig.me'
alias ..='cd ..'
Aliases and Arguments
A common misconception is that aliases can accept arguments like functions. They cannot. However, you can use shell history expansion or include $@ inside a quoted string if you define the alias as a function (see later). For example, an alias like alias grep='grep --color=auto' works because the arguments are appended automatically. But for more complex argument handling, use a function.
Useful Alias Examples
# Navigation
alias ..='cd ..'
alias ...='cd ../..'
alias home='cd ~'
# Git shortcuts
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gl='git log --oneline --graph'
# File operations
alias rm='rm -i' # interactive removal
alias cp='cp -i' # interactive copy
alias mv='mv -i' # interactive move
# Safety
alias sudo='sudo ' # trailing space allows alias expansion for the next word
How to Use Functions
Defining a Bash Function
Bash functions are defined using either the function keyword or simply name() { ... }. The standard syntax is:
# Using the function keyword
function myfunc {
echo "Hello, $1"
}
# Using parentheses
myfunc() {
echo "Hello, $1"
}
You call a function just like any other command: myfunc World prints Hello, World.
Function Arguments
Inside a function, the arguments passed are accessible via $1, $2, ..., $@ (all arguments), and $# (number of arguments). This makes functions far more powerful than aliases.
function mcd() {
mkdir -p "$1" && cd "$1"
}
# Usage: mcd new_project
Return Values and Exit Codes
Functions can return an integer exit code (0 for success, non-zero for failure) using the return keyword. This allows conditional usage in scripts.
function is_even() {
if (( $1 % 2 == 0 )); then
return 0
else
return 1
fi
}
if is_even 4; then
echo "Even"
fi
Note: return only sets the exit status, it does not output a value. To return data, use echo and capture with command substitution:
function get_date() {
echo "$(date +%Y-%m-%d)"
}
today=$(get_date)
echo "Today is $today"
Local Variables
Use the local keyword to declare variables that are scoped to the function, preventing pollution of the global namespace.
function backup_file() {
local file="$1"
local backup="${file}.bak"
cp "$file" "$backup"
echo "Backup created: $backup"
}
Practical Function Examples
# Create a directory and enter it (mcd)
function mcd() {
mkdir -p "$1" && cd "$1"
}
# Extract various archive formats
function extract() {
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2) tar xjf "$1" ;;
*.tar.gz) tar xzf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.rar) unrar x "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar xf "$1" ;;
*.tbz2) tar xjf "$1" ;;
*.tgz) tar xzf "$1" ;;
*.zip) unzip "$1" ;;
*.Z) uncompress "$1" ;;
*) echo "'$1' cannot be extracted" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# Find file by name, ignoring case
function findf() {
find . -iname "*$1*"
}
# Git commit with a message