Shell Aliases and Functions: Speed Up Daily Commands
In this tutorial, you'll learn shell aliases and functions including creating, organizing, and managing aliases across shells, argument passing, and sharing alias collections with your team.
Why Aliases Matter
You type the same commands dozens of times a day: git status, docker ps, npm run dev, ssh user@server. Each command takes seconds to type. Aliases cut that to a few keystrokes. Shell functions extend this to complex operations with arguments. Together, they eliminate friction and reduce typos.
By the end of this guide, you will create aliases and functions, organize them across files, handle arguments, and share configurations with your team.
What Are Shell Aliases and Functions?
An alias is a shortcut for a command or group of commands. A shell function is a named block of code that accepts arguments and can implement logic.
flowchart LR A[Shell Shortcuts] --> B[Aliases] A --> C[Functions] B --> D[Simple: gs = git status] B --> E[With flags: ll = ls -la] C --> F[With args: mkcd dir] C --> G[Logic: docker-ps with formatting] C --> H[Composition: deploy = build + push]
Simple Aliases
# ~/.zshrc or ~/.bashrc
# Git shortcuts
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gl='git log --oneline --graph --decorate --all'
alias gco='git checkout'
alias gb='git branch'
alias gd='git diff'
alias gpl='git pull'
# File listing
alias ls='eza --icons' # Modern ls with icons
alias ll='eza -la --icons' # Detailed listing
alias lt='eza --tree' # Tree view
alias la='eza -a' # All files
# Navigation
alias ..='cd ..'
alias ...='cd ../..'
alias ~='cd ~'
alias -- -='cd -' # Go back to last directory
# Docker
alias d='docker'
alias dc='docker compose'
alias dps='docker ps'
alias dpsa='docker ps -a'
alias di='docker images'
# Misc
alias cat='bat' # Syntax-aware cat
alias top='htop' # Better process viewer
alias df='df -h' # Human-readable disk usage
alias du='du -h --max-depth=1'
alias grep='grep --color=auto'
alias rm='rm -i' # Interactive removal
Expected Behavior
$ gs
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
Aliases with Arguments
Plain aliases cannot handle arguments. For that, use shell functions.
# Function: mkcd — create and enter directory
mkcd() {
mkdir -p "$1" && cd "$1"
}
# Function: gac — git add and commit
gac() {
if [ -z "$1" ]; then
echo "Usage: gac <commit-message>"
return 1
fi
git add -A && git commit -m "$1"
}
# Function: tml — list all tmux sessions
tml() {
tmux ls 2>/dev/null || echo "No tmux sessions running"
}
# Function: findport — find process using a port
findport() {
lsof -i :"$1" | grep LISTEN
}
# Function: extract — extract any archive
extract() {
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2) tar xjf "$1" ;;
*.tar.gz) tar xzf "$1" ;;
*.tar.xz) tar xJf "$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 "Unknown archive format: $1" ;;
esac
else
echo "File not found: $1"
fi
}
Expected Behavior
$ mkcd new-project
$ pwd
/home/user/new-project
$ gac "Fix login bug"
[main a1b2c3d] Fix login bug
3 files changed, 42 insertions(+), 12 deletions(-)
Advanced Functions
Docker Management
# Remove all stopped containers and unused images
docker-clean() {
echo "Removing stopped containers..."
docker container prune -f
echo "Removing dangling images..."
docker image prune -f
echo "Removing unused volumes..."
docker volume prune -f
echo "Done!"
}
# Enter a running container
dexec() {
local container="${1:-$(docker ps --format '{{.Names}}' | fzf)}"
if [ -n "$container" ]; then
docker exec -it "$container" /bin/bash 2>/dev/null || docker exec -it "$container" /bin/sh
fi
}
# Docker compose shortcuts
dcup() {
docker compose up -d "$@"
docker compose logs -f
}
Git Workflow
# Interactive branch checkout with fzf
gcof() {
local branch=$(git branch --all | grep -v HEAD | fzf --preview 'git log --oneline --graph --decorate --all {1}' | sed 's/.* //' | sed 's#remotes/[^/]*/##')
if [ -n "$branch" ]; then
git checkout "$branch"
fi
}
# Squash last N commits
gsquash() {
local count="${1:-2}"
git reset --soft HEAD~"$count" && git commit --edit
}
# Find and delete merged branches
gclean() {
git branch --merged | grep -v "\*\|main\|master" | xargs -r git branch -d
}
System Utilities
# Show disk usage for current directory (sorted)
dusort() {
du -sh ./* | sort -rh | head -"${1:-10}"
}
# Find the largest files
largest() {
find . -type f -exec ls -lh {} + 2>/dev/null | sort -k5 -rh | head -"${1:-10}"
}
# Generate a random password
genpass() {
local length="${1:-32}"
openssl rand -base64 48 | cut -c1-"$length"
}
# Weather forecast
weather() {
curl -s "wttr.in/${1:-}" | head -n 27
}
Organizing Aliases
Split aliases into separate files for maintainability:
~/.dotfiles/
├── zsh/
│ ├── .zshrc # Main config
│ ├── aliases.zsh # All aliases
│ ├── functions.zsh # All functions
│ ├── exports.zsh # Environment variables
│ ├── plugins.zsh # Plugin configuration
│ └── completion.zsh # Tab completion
# ~/.zshrc
source ~/.dotfiles/zsh/aliases.zsh
source ~/.dotfiles/zsh/functions.zsh
source ~/.dotfiles/zsh/exports.zsh
Conditional Aliases
# Only if the command exists
if command -v eza &> /dev/null; then
alias ls='eza --icons'
elif command -v exa &> /dev/null; then
alias ls='exa --icons'
else
alias ll='ls -la'
fi
# Platform-specific
case "$OSTYPE" in
darwin*)
alias uuid='uuidgen'
alias flushdns='dscacheutil -flushcache'
;;
linux*)
alias uuid='cat /proc/sys/kernel/random/uuid'
alias open='xdg-open'
;;
esac
Overriding Built-in Commands
# Safer versions of dangerous commands
alias rm='rm -i' # Ask before delete
alias cp='cp -i' # Ask before overwrite
alias mv='mv -i' # Ask before overwrite
# Or use trash instead of rm (macOS)
if command -v trash &> /dev/null; then
alias rm='trash'
fi
# ls with colors always on
if [[ "$OSTYPE" == "darwin"* ]]; then
alias ls='ls -G'
fi
Loading Aliases on Demand
# Lazy-load Docker aliases (only when docker is first used)
docker() {
unfunction "$0"
source ~/.dotfiles/zsh/docker-aliases.zsh
$0 "$@"
}
# Lazy-load Node.js aliases
npm() {
unfunction "$0"
source ~/.dotfiles/zsh/node-aliases.zsh
$0 "$@"
}
Common Errors
| Problem | Cause | Fix |
|---|---|---|
command not found after alias definition |
Alias not sourced | Run source ~/.zshrc or restart shell |
| Alias not working with sudo | sudo does not inherit aliases | Use sudo -E or create a function |
| Alias expansion not visible | which does not work for aliases |
Use type aliasname |
| Function not found in script | Functions not exported by default | Use export -f functionname or define in script |
| Conflicting aliases | Same alias defined in multiple files | Check all sourced files for duplicates |
Practice Questions
1. How do you create a simple alias in shell?
alias name='command' in .zshrc or .bashrc.
2. What is the difference between an alias and a function?
Aliases replace text. Functions can accept arguments, implement logic, and include multiple commands.
3. How do you pass an argument to a shell function?
Access arguments with $1, $2, etc. inside the function body.
4. How do you make an alias permanent?
Add the alias definition to your shell's config file (~/.zshrc or ~/.bashrc).
5. How do you organize aliases across multiple files?
Use source in your main config file to load alias files from a directory (e.g., ~/.dotfiles/zsh/).
Challenge
Create a comprehensive aliases file (~/.dotfiles/zsh/aliases.zsh) with at least 20 aliases and 10 functions organized into sections: Git, Docker, file management, navigation, system utilities, and project-specific. Include conditional loading based on OS and available commands.
Real-World Task
Audit your daily command usage for one day. Write down every command you type more than once. Create aliases for the top 10 most frequent commands. Create functions for any multi-step workflows (e.g., deploying, running tests with cleanup, starting a project environment). Version-control your aliases file and share it with your team.
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro