Command Line Productivity Tips

Level Up Your Linux Terminal Skills

1. Master Command History Navigation

Your shell's history is a goldmine of productivity. Instead of retyping commands, learn to navigate and search through your history efficiently.

Reverse Search (Ctrl+R)

Press Ctrl+R and start typing any part of a previous command. The shell will search backward through your history and display matches. Press Ctrl+R again to cycle through multiple matches.

Example: Search for docker commands
(reverse-i-search)`docker': docker-compose up -d

History Expansion Shortcuts

!!          # Repeat last command
!$          # Last argument of previous command
!^          # First argument of previous command
!*          # All arguments of previous command
!-2         # Command from 2 lines ago
!grep       # Last command starting with 'grep'
Pro Tip: Combine with sudo for quick privilege escalation: sudo !! runs your last command with root privileges.

2. Leverage Aliases and Functions

Stop typing repetitive commands. Create aliases for your most common tasks and functions for more complex operations.

Useful Aliases

Add these to your ~/.bashrc or ~/.zshrc:

# Navigation shortcuts
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

# Enhanced ls commands
alias ll='ls -alFh'
alias la='ls -A'
alias l='ls -CF'

# 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'

# Safety nets
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Quick edits
alias bashrc='vim ~/.bashrc'
alias vimrc='vim ~/.vimrc'

# System monitoring
alias ports='netstat -tulanp'
alias meminfo='free -m -l -t'
alias psmem='ps auxf | sort -nr -k 4 | head -10'
alias pscpu='ps auxf | sort -nr -k 3 | head -10'

Powerful Functions

Functions allow for more complex logic with parameters:

# Create directory and cd into it
mkcd() {
    mkdir -p "$1" && cd "$1"
}

# Extract any archive
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"     ;;
            *.zip)       unzip "$1"      ;;
            *.Z)         uncompress "$1" ;;
            *)           echo "'$1' cannot be extracted" ;;
        esac
    fi
}

# Find and kill process by name
killp() {
    ps aux | grep -i "$1" | grep -v grep | awk '{print $2}' | xargs kill -9
}

# Backup file with timestamp
backup() {
    cp "$1"{,.backup-$(date +%Y%m%d-%H%M%S)}
}

3. Become a Text Processing Wizard

Master these tools to manipulate text and data directly from the command line.

awk for Column Operations

# Print specific columns
df -h | awk '{print $1, $5}'

# Sum numbers in a column
cat numbers.txt | awk '{sum += $1} END {print sum}'

# Filter based on column value
ps aux | awk '$3 > 50 {print $0}'  # CPU usage > 50%

sed for Stream Editing

# Replace text in file
sed 's/old/new/g' file.txt

# Edit in place with backup
sed -i.bak 's/old/new/g' file.txt

# Delete lines matching pattern
sed '/pattern/d' file.txt

# Print specific line range
sed -n '10,20p' file.txt

grep with Context

# Show 3 lines before and after match
grep -C 3 "pattern" file.txt

# Recursive search excluding directories
grep -r --exclude-dir={.git,node_modules} "pattern" .

# Count matches
grep -c "pattern" file.txt

# Case-insensitive with line numbers
grep -in "pattern" file.txt

4. Process and Job Control

Manage running processes efficiently with job control commands.

Background and Foreground Jobs

# Run command in background
long_running_command &

# Send current job to background
Ctrl+Z
bg

# Bring job to foreground
fg %1

# List all jobs
jobs

# Disown a job (keeps running after logout)
disown %1

# Run command immune to hangups
nohup long_running_command &
Pro Tip: Use screen or tmux for persistent sessions that survive disconnections. They're essential for remote work.

5. Find Files Like a Pro

The find command is incredibly powerful when you know its options.

Advanced find Patterns

# Find files modified in last 7 days
find . -type f -mtime -7

# Find large files (>100MB)
find . -type f -size +100M

# Find and execute command on results
find . -name "*.log" -exec rm {} \;

# Find with multiple conditions
find . -type f -name "*.py" -size +1M -mtime -30

# Find files by permissions
find . -type f -perm 0777

# Find and copy to directory
find . -name "*.jpg" -exec cp {} /backup/ \;

# Delete empty directories
find . -type d -empty -delete

Quick Alternative: locate

For faster searching, use locate (requires database update with updatedb):

locate filename
locate -i filename  # case-insensitive
locate -c filename  # count matches

6. Command Chaining and Pipelines

Combine commands effectively to create powerful one-liners.

Operators

# Run sequentially regardless of success
command1 ; command2

# Run second only if first succeeds
command1 && command2

# Run second only if first fails
command1 || command2

# Pipe output as input
command1 | command2

# Append to file
command >> file.txt

# Redirect stderr and stdout
command &> file.txt

# Redirect stderr to stdout
command 2>&1

Practical Examples

# Monitor log file in real-time with filtering
tail -f /var/log/syslog | grep -i error

# Find largest directories
du -h --max-depth=1 | sort -hr | head -10

# Process substitution
diff <(ls dir1) <(ls dir2)

# Count unique IP addresses in log
cat access.log | awk '{print $1}' | sort | uniq -c | sort -nr

# Monitor command output every 2 seconds
watch -n 2 'df -h'

7. Clipboard Integration

Connect your terminal with your system clipboard for seamless workflows.

# Install clipboard utilities
# Ubuntu/Debian
sudo apt install xclip

# Copy command output to clipboard
cat file.txt | xclip -selection clipboard

# Paste from clipboard
xclip -selection clipboard -o

# Create aliases for convenience
alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'

# Usage
ls -la | pbcopy
pbpaste > output.txt

8. Customize Your Prompt

A well-designed prompt provides valuable context at a glance.

Enhanced PS1 Examples

# Show user, host, and full path
export PS1="\u@\h:\w\$ "

# Add colors
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

# Include git branch (requires git-prompt)
source /usr/share/git-core/contrib/completion/git-prompt.sh
export PS1='\u@\h:\w$(__git_ps1 " (%s)")\$ '

# Show exit status of last command
export PS1='\[\033[0;32m\]\u@\h\[\033[0m\]:\[\033[0;34m\]\w\[\033[0m\] \[\033[0;31m\]$?\[\033[0m\] \$ '
Pro Tip: Consider using Starship prompt for a modern, feature-rich prompt that works across shells. Install from starship.rs

9. Shell Scripting Shortcuts

Write better scripts with these techniques.

Parameter Expansion

# Default values
${var:-default}        # Use default if var is unset
${var:=default}        # Assign default if var is unset

# String manipulation
${var#pattern}         # Remove shortest match from beginning
${var##pattern}        # Remove longest match from beginning
${var%pattern}         # Remove shortest match from end
${var%%pattern}        # Remove longest match from end

# Example: Extract filename and extension
filename="${file##*/}"
extension="${file##*.}"
basename="${file%.*}"

Here Documents

# Multi-line input
cat << EOF > config.txt
Setting1=value1
Setting2=value2
Setting3=value3
EOF

# Execute multiple commands via SSH
ssh user@host << 'ENDSSH'
cd /var/www
git pull
sudo systemctl restart nginx
ENDSSH

10. Performance Monitoring One-Liners

Quick commands for system diagnostics.

# Top 10 memory-consuming processes
ps aux --sort=-%mem | head -11

# Top 10 CPU-consuming processes
ps aux --sort=-%cpu | head -11

# Disk usage of current directory sorted
du -h --max-depth=1 | sort -hr

# Monitor network connections
watch -n 1 'netstat -an | grep ESTABLISHED | wc -l'

# Check listening ports
netstat -tlnp | grep LISTEN

# Real-time bandwidth monitoring (requires iftop)
sudo iftop -i eth0

# I/O statistics
iostat -x 1

# System load over time
uptime

11. Keyboard Shortcuts Every User Should Know

These shortcuts will dramatically speed up your terminal work.

Navigation
Ctrl+A          # Move to beginning of line
Ctrl+E          # Move to end of line
Ctrl+B          # Move back one character
Ctrl+F          # Move forward one character
Alt+B           # Move back one word
Alt+F           # Move forward one word
Editing
Ctrl+K          # Cut from cursor to end of line
Ctrl+U          # Cut from cursor to beginning of line
Ctrl+W          # Cut word before cursor
Ctrl+Y          # Paste last cut text
Ctrl+T          # Swap last two characters
Alt+T           # Swap last two words
Alt+U           # Uppercase from cursor to end of word
Alt+L           # Lowercase from cursor to end of word
Control
Ctrl+C          # Terminate current command
Ctrl+Z          # Suspend current command
Ctrl+D          # Exit shell (EOF)
Ctrl+L          # Clear screen
Ctrl+R          # Reverse search history
Ctrl+G          # Escape from reverse search

12. Quick Configuration Tweaks

Add these to your ~/.bashrc or ~/.zshrc for immediate productivity gains.

# Infinite history
export HISTSIZE=
export HISTFILESIZE=

# Ignore duplicates and commands starting with space
export HISTCONTROL=ignoreboth

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

# Auto-correct minor spelling errors in cd
shopt -s cdspell

# Enable recursive globbing with **
shopt -s globstar

# Check window size after each command
shopt -s checkwinsize

# Better tab completion
bind 'set completion-ignore-case on'
bind 'set show-all-if-ambiguous on'
bind 'set mark-symlinked-directories on'

# Colorful grep output
export GREP_OPTIONS='--color=auto'

# Set better less options
export LESS='-R -X -F'
Note: After modifying your shell configuration, run source ~/.bashrc (or source ~/.zshrc) to reload the changes without restarting your terminal.