Bash/Zsh Bash/Zsh Bash History: Commands, Configuration & Best Practices

Bash History: Commands, Configuration & Best Practices

AS
Aman Saurav
| Dec 25, 2024 |
read
#bash #history #productivity #configuration

Bash History: Commands, Configuration & Best Practices

Command history is one of Bash’s most powerful productivity features. Learning to effectively use and configure history can save you countless hours and keystrokes. This guide covers everything from basic usage to advanced configuration.

Basic History Commands

View Command History

# Show all history
history

# Show last 20 commands
history 20

# Show history with timestamps (if configured)
history

Sample output:

  1  ls -la
  2  cd /var/log
  3  grep error app.log
  4  vim config.txt
  5  history

Search History

# Search backwards (Ctrl+R)
# Type Ctrl+R, then start typing your search term

# Search forward (Ctrl+S)
# May need to disable flow control first: stty -ixon

# Show all commands containing "git"
history | grep git

# Show last 50 commands containing "docker"
history 50 | grep docker

History Navigation Shortcuts

Keyboard Shortcuts

Shortcut Action
Ctrl+R Reverse search through history
Ctrl+S Forward search (after Ctrl+R)
Ctrl+P or Previous command
Ctrl+N or Next command
Alt+< First command in history
Alt+> Last command (current line)
!! Repeat last command
!n Execute command number n
!-n Execute nth command from end
!string Execute most recent command starting with “string”
!?string Execute most recent command containing “string”

Practical Examples

# Repeat last command
!!

# Repeat last command with sudo
sudo !!

# Execute command #42 from history
!42

# Execute last command starting with "git"
!git

# Execute last command containing "docker"
!?docker

# Use arguments from previous command
cp file.txt backup/
ls !$  # !$ = last argument (backup/)

# Use all arguments from previous command
mv file1.txt file2.txt /backup/
ls !*  # !* = all arguments

History Configuration

Environment Variables

HISTSIZE - Number of commands in memory

# In ~/.bashrc or ~/.bash_profile
export HISTSIZE=10000  # Default is usually 500

HISTFILESIZE - Number of commands in history file

# In ~/.bashrc or ~/.bash_profile
export HISTFILESIZE=20000  # Default is usually 500

HISTFILE - Location of history file

# Default: ~/.bash_history
export HISTFILE=~/.bash_history

# Use custom location
export HISTFILE=~/.my_custom_history

HISTCONTROL - Control what gets saved

# Ignore duplicate commands
export HISTCONTROL=ignoredups

# Ignore commands starting with space
export HISTCONTROL=ignorespace

# Combine both
export HISTCONTROL=ignoreboth

# Ignore duplicates and erase older duplicates
export HISTCONTROL=erasedups

HISTIGNORE - Ignore specific commands

# Don't save ls, pwd, exit, or history commands
export HISTIGNORE="ls:pwd:exit:history"

# Ignore multiple patterns
export HISTIGNORE="ls:cd:pwd:exit:date:* --help"

HISTTIMEFORMAT - Add timestamps

# Add timestamps to history
export HISTTIMEFORMAT="%F %T "  # Format: YYYY-MM-DD HH:MM:SS

# Custom format
export HISTTIMEFORMAT="%d/%m/%y %T "  # Format: DD/MM/YY HH:MM:SS

Output with timestamps:

  1  2024-12-25 10:30:15 ls -la
  2  2024-12-25 10:31:42 cd /var/log
  3  2024-12-25 10:32:18 grep error app.log

Complete Configuration Example

Add this to your ~/.bashrc:

# History Configuration
# =====================

# Increase history size
export HISTSIZE=50000
export HISTFILESIZE=100000

# Add timestamps
export HISTTIMEFORMAT="%F %T "

# Avoid duplicates
export HISTCONTROL=ignoredups:erasedups

# Ignore common commands
export HISTIGNORE="ls:ll:cd:pwd:exit:date:clear:history"

# Append to history file, don't overwrite
shopt -s histappend

# Save multi-line commands as one command
shopt -s cmdhist

# Save history after each command (not just on exit)
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"

Advanced History Techniques

1. Sync History Across Multiple Terminals

# Add to ~/.bashrc
shopt -s histappend
PROMPT_COMMAND="history -a; history -c; history -r"

Explanation:

  • history -a - Append new commands to history file
  • history -c - Clear current session history
  • history -r - Read history file into current session

2. Unlimited History

# Add to ~/.bashrc
export HISTSIZE=-1
export HISTFILESIZE=-1

3. Separate History Per Directory

# Add to ~/.bashrc
function cd() {
    builtin cd "$@"
    export HISTFILE=~/.bash_history_$(pwd | sed 's/\//_/g')
}

4. Backup History Regularly

#!/bin/bash
# Add to crontab: 0 0 * * * /path/to/backup_history.sh

DATE=$(date +%Y%m%d)
cp ~/.bash_history ~/.bash_history_backup_$DATE

# Keep only last 30 days of backups
find ~/.bash_history_backup_* -mtime +30 -delete

5. Search History with fzf (Fuzzy Finder)

# Install fzf first: https://github.com/junegunn/fzf

# Add to ~/.bashrc
# Ctrl+R for fuzzy history search
bind '"\C-r": "\C-x1\e^\er"'
bind -x '"\C-x1": __fzf_history'

__fzf_history() {
    READLINE_LINE=$(history | fzf --tac --tiebreak=index | sed 's/^ *[0-9]* *//')
    READLINE_POINT=${#READLINE_LINE}
}

History Management Commands

Clear History

# Clear current session history
history -c

# Delete specific entry (e.g., entry #42)
history -d 42

# Clear history file
cat /dev/null > ~/.bash_history

# Clear both memory and file
history -c && history -w

Write History

# Write current session to history file
history -w

# Append current session to history file
history -a

# Read history file into current session
history -r

Practical Use Cases

1. Find and Re-run Complex Commands

# Find that long docker command you ran yesterday
history | grep docker | grep compose

# Then execute it
!1234  # Use the number from history

2. Audit Your Command Usage

# Most used commands
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10

# Commands run today
history | grep "$(date +%Y-%m-%d)"

3. Create Aliases from History

# Find frequently used commands
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -5

# Create aliases for them in ~/.bashrc
alias gs='git status'
alias gp='git pull'
alias dc='docker-compose'

4. Recover Lost Commands

# If you accidentally cleared terminal
history | tail -20

# If terminal crashed
cat ~/.bash_history | tail -50

Zsh History Differences

If you use Zsh instead of Bash:

# In ~/.zshrc

# History file location
HISTFILE=~/.zsh_history

# History size
HISTSIZE=50000
SAVEHIST=100000

# Options
setopt EXTENDED_HISTORY          # Write timestamp
setopt HIST_EXPIRE_DUPS_FIRST    # Expire duplicates first
setopt HIST_IGNORE_DUPS          # Don't record duplicates
setopt HIST_IGNORE_SPACE         # Ignore commands starting with space
setopt HIST_VERIFY               # Show command before executing from history
setopt SHARE_HISTORY             # Share history between sessions

Security Considerations

1. Prevent Sensitive Commands from Being Saved

# Start command with space (if HISTCONTROL=ignorespace)
 mysql -u root -p secret_password

# Or temporarily disable history
set +o history
# Run sensitive commands
mysql -u root -p secret_password
set -o history  # Re-enable

2. Clear Sensitive Commands

# Remove specific command
history -d 1234

# Edit history file directly
vim ~/.bash_history

3. Encrypt History File

# Encrypt
gpg -c ~/.bash_history

# Decrypt when needed
gpg -d ~/.bash_history.gpg > ~/.bash_history

Download Configuration Files

📦 Download History Configuration Pack (ZIP)

The ZIP includes:

  • .bashrc_history - Optimized Bash history configuration
  • .zshrc_history - Optimized Zsh history configuration
  • backup_history.sh - Automated history backup script
  • history_stats.sh - Analyze your command usage
  • README.md - Installation and usage guide

Video Tutorial

Quick Reference

# View history
history              # All history
history 20           # Last 20 commands

# Search
Ctrl+R               # Reverse search
history | grep term  # Grep search

# Execute
!!                   # Last command
!42                  # Command #42
!git                 # Last command starting with "git"

# Configuration (~/.bashrc)
export HISTSIZE=50000
export HISTFILESIZE=100000
export HISTTIMEFORMAT="%F %T "
export HISTCONTROL=ignoreboth
export HISTIGNORE="ls:cd:pwd:exit"
shopt -s histappend

# Management
history -c           # Clear session
history -w           # Write to file
history -d 42        # Delete entry #42

Summary

Effective history management provides:

  • ✅ Quick access to previous commands
  • ✅ Reduced typing and errors
  • ✅ Command usage analytics
  • ✅ Audit trail for troubleshooting
  • ✅ Productivity boost

Configure your history settings once and enjoy the benefits forever!


Download Exercise Files

Get the source code, datasets, and cheat sheet for this lesson.

Download Resources