Bash
Bash (Bourne Again Shell) is a Unix shell and command language that provides a command-line interface for interacting with the operating system. Originally developed as a free software replacement for the Bourne shell, Bash has become the default shell for most Linux distributions and macOS.
Core Concepts
Section titled “Core Concepts”Shell Environment
Section titled “Shell Environment”Bash operates as both an interactive command interpreter and a scripting language. It reads commands from the terminal or script files, executes them, and returns results.
Configuration Files
Section titled “Configuration Files”Bash uses several configuration files that execute at different times:
- ~/.bashrc: Executed for interactive, non-login shells
- ~/.bash_profile: Executed for login shells
- ~/.bash_aliases: Custom alias definitions (sourced by ~/.bashrc)
Variables and Environment
Section titled “Variables and Environment”Bash maintains environment variables that control shell behavior and store system information.
# Set environment variablesexport PATH="/usr/local/bin:$PATH"export EDITOR="nvim"
# Display variablesecho $HOMEecho $PATHEssential Bash Features
Section titled “Essential Bash Features”History Management
Section titled “History Management”Bash maintains a command history for efficient command recall and editing.
# History settingsHISTCONTROL=ignoreboth # Ignore duplicates and lines starting with spaceHISTSIZE=1000 # Commands to remember in sessionHISTFILESIZE=2000 # Commands to store in history file
# History navigation!! # Execute last command!n # Execute command number n!string # Execute last command starting with stringCtrl+R # Reverse search through historyCommand Line Editing
Section titled “Command Line Editing”Bash provides powerful command line editing capabilities using Emacs-style key bindings by default.
# NavigationCtrl+A # Move to beginning of lineCtrl+E # Move to end of lineCtrl+B # Move backward one characterCtrl+F # Move forward one character
# EditingCtrl+U # Delete from cursor to beginning of lineCtrl+K # Delete from cursor to end of lineCtrl+W # Delete word before cursorPractical Aliases
Section titled “Practical Aliases”Aliases create shortcuts for frequently used commands, making command-line work more efficient. Here are organized categories of useful aliases:
Navigation Shortcuts
Section titled “Navigation Shortcuts”# Multi-level directory navigationalias ..="cd .."alias ...="cd ../.."alias ....="cd ../../.."alias .....="cd ../../../.."
# Quick directory accessalias ~="cd ~"alias -- -="cd -" # Return to previous directoryalias home="cd ~"alias 1="cd ~"
# Project-specific shortcutsalias d="cd ~/Documents/Dropbox"alias dl="cd ~/Downloads"alias dt="cd ~/Desktop"alias p="cd ~/projects"File Operations with Safety
Section titled “File Operations with Safety”# Verbose and interactive file operationsalias mv='mv -v' # Verbose movealias rm='rm -i -v' # Interactive and verbose removealias cp='cp -v' # Verbose copy
# Enhanced ls commandsalias ll='ls -alF' # Long format with file typesalias la='ls -A' # Show hidden filesalias l='ls -CF' # Compact format with file typesGit Integration
Section titled “Git Integration”# Quick git accessalias g="git"
# Common git workflows would use the full commands# but having 'g' saves keystrokes for frequent usersSystem Information
Section titled “System Information”# Network informationalias ip="dig +short myip.opendns.com @resolver1.opendns.com"alias localip="ipconfig getifaddr en0"alias myip='curl -s ifconfig.me'
# System monitoringalias mem='free -h'alias disk='df -h'alias top='htop'alias week='date +%V'Development and Docker
Section titled “Development and Docker”# Docker shortcutsalias d='docker'alias dc='docker-compose'alias dcu='docker-compose up -d'alias dcd='docker-compose down'alias dcr='docker-compose restart'alias dcl='docker-compose logs -f'
# Service managementalias services='cd /home/data && ls -la'alias update='sudo apt update && sudo apt upgrade -y'alias cleanup='sudo apt autoremove -y && sudo apt autoclean'tmux Session Management
Section titled “tmux Session Management”# tmux shortcuts for session managementalias t='tmux'alias tl='tmux list-sessions'alias ta='tmux attach-session -t'alias tn='tmux new-session -s'alias tk='tmux kill-session -t'alias treload='tmux source-file ~/.tmux.conf'Advanced Features
Section titled “Advanced Features”Command Substitution and Piping
Section titled “Command Substitution and Piping”# Command substitutioncurrent_dir=$(pwd)echo "Currently in: $current_dir"
# Piping and redirectionps aux | grep nginx # Pipe output to grepls -la > file_list.txt # Redirect output to filecommand 2> error.log # Redirect errors to fileFunctions vs Aliases
Section titled “Functions vs Aliases”While aliases work for simple command substitutions, functions provide more flexibility:
# Function for complex operationsweather() { curl "wttr.in/${1:-MSP}"}
# Usage: weather NYCBasic Scripting
Section titled “Basic Scripting”Bash scripts automate repetitive tasks and can be saved as executable files:
#!/bin/bash# Simple backup script
backup_dir="/home/backup"source_dir="/home/documents"
if [ ! -d "$backup_dir" ]; then mkdir -p "$backup_dir"fi
cp -r "$source_dir" "$backup_dir/$(date +%Y%m%d)"echo "Backup completed: $(date)"Script basics:
- Start with
#!/bin/bash(shebang) - Make executable with
chmod +x script.sh - Use variables, conditionals, and loops for automation
- Test scripts before running on important data
Conditional Execution
Section titled “Conditional Execution”# Execute commands conditionallycommand1 && command2 # Execute command2 only if command1 succeedscommand1 || command2 # Execute command2 only if command1 failsTab Completion
Section titled “Tab Completion”Bash provides intelligent command and filename completion:
# Enable programmable completion featuresif ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion fifi
# Usage: Type partial command + Tab for completion# git che<Tab> → git checkout# cd Doc<Tab> → cd Documents/Shell Options and Behavior
Section titled “Shell Options and Behavior”Useful Shell Options
Section titled “Useful Shell Options”# Append to history file instead of overwritingshopt -s histappend
# Check window size after each commandshopt -s checkwinsize
# Enable recursive globbing with **shopt -s globstarPrompt Customization
Section titled “Prompt Customization”The PS1 variable controls the shell prompt appearance:
# Basic colored promptPS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
# Components:# \u = username# \h = hostname# \w = working directory# \$ = $ for users, # for rootBest Practices
Section titled “Best Practices”Alias Organization
Section titled “Alias Organization”- Keep aliases in
~/.bash_aliasesfor better organization - Use descriptive names that won’t conflict with existing commands
- Group related aliases together with comments
- Test aliases before adding them to avoid breaking existing workflows
Safety Considerations
Section titled “Safety Considerations”- Use interactive flags (
-i) for destructive operations likerm - Include verbose flags (
-v) to see what commands are doing - Avoid aliasing critical system commands unless you’re certain of the behavior
Performance Tips
Section titled “Performance Tips”- Use
HISTCONTROL=ignorebothto avoid cluttering history with duplicates - Set appropriate
HISTSIZEandHISTFILESIZEvalues - Use command completion with
Tabkey for efficiency
Integration with Development Workflow
Section titled “Integration with Development Workflow”Bash integrates seamlessly with development tools and workflows. See related notes for deeper coverage of specific tools:
Version Control: Git commands and aliases for streamlined version control operations
Command Line Tools: Reference CLI Commands and Cheat Sheet for comprehensive command documentation
Container Management: Docker and docker-compose aliases for rapid container orchestration
Session Management: tmux integration for persistent terminal sessions across development work
System Administration: Service monitoring, log viewing, and system maintenance commands
Network Diagnostics: Quick access to network information and connectivity testing
Text Processing: Integration with tools like Emmet Cheat Sheet for efficient text expansion workflows
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”Aliases not working after restart:
# Reload bash configurationsource ~/.bashrc# Or use the aliasrestartbashCommand not found:
# Check if command existswhich command_nametype command_name
# Check PATH variableecho $PATHHistory not saving:
# Ensure history settings are correctecho $HISTSIZEecho $HISTFILESIZEshopt | grep histThe shell environment becomes an extension of your development workflow when properly configured. Thoughtful alias creation and bash customization can significantly improve productivity by reducing keystrokes and providing quick access to frequently used commands and locations.