Overview
The clear command is one of the simplest yet most frequently used commands in Linux. It clears the terminal screen by sending control sequences to the terminal emulator, providing a clean workspace free from previous command output. While deceptively simple, clear is essential for maintaining a tidy work environment, especially during long interactive sessions or when demonstrating commands.
What Clear Actually Does:
- Sends terminal control sequences (from terminfo database)
- Clears the visible screen area
- Moves cursor to top-left position (home position)
- Does NOT erase scrollback buffer in most terminals
- Does NOT clear command history
- Works by consulting the TERM environment variable
Common Uses:
- Declutter terminal after long output
- Start fresh for a new task or demonstration
- Hide sensitive information from shoulder surfers
- Create visual separation between work sessions
- Clear screen before running monitoring commands
- Prepare clean screen for presentations or screen sharing
Most terminals support Ctrl+L as a keyboard shortcut to clear the screen. This is often faster than typing clear and works in most shells and many applications (like vim, less, etc.).
The clear command uses the terminfo database to look up the appropriate control sequences for your terminal type (defined by the TERM environment variable). For most modern terminals (xterm, gnome-terminal, etc.), it sends escape sequences like ESC[H (move to home) and ESC[2J (clear screen). Different terminal types may use different sequences, which is why clear consults terminfo rather than hardcoding the sequences.
Common Options
| Option | Description |
|---|---|
| -V | Display version information |
| -x | Do not attempt to clear scrollback buffer (some versions) |
| -T type | Specify terminal type (overrides TERM variable) |
clear with no arguments.
Detailed Examples
Basic Screen Clearing
The most common and straightforward use of clear.
# Your terminal is cluttered with output
$ ls -la
$ ps aux
$ netstat -tuln
# ... lots of output scrolling by ...
# Clear the screen
$ clear
clear and pressing Enter clears all the visible text from your terminal window and positions your cursor at the top-left corner. The previous output is typically still in your scrollback buffer (you can scroll up to see it), but the visible screen is clean.
clear, use Ctrl+L - it's much faster and works in most situations!
Using Ctrl+L Keyboard Shortcut
The faster, more efficient way to clear your screen using a keyboard shortcut.
# Instead of typing 'clear', just press Ctrl+L
[Ctrl+L]
# Works while you're in the middle of typing a command too
$ long-command-name-that-you-are-ty[Ctrl+L]
# The partial command is preserved and screen is cleared
$ long-command-name-that-you-are-ty
Ctrl+L is a readline keyboard shortcut that clears the screen. The major advantage is that if you're in the middle of typing a command, Ctrl+L clears the screen but preserves your partially-typed command. If you typed clear instead, you'd lose what you were typing.
Ctrl+L to clear the clutter while keeping your command intact.
Clear in Shell Scripts
Using clear in scripts to create cleaner, more professional-looking output.
#!/bin/bash
# System monitoring script with clear screen
while true; do
# Clear screen before each update
clear
# Display header
echo "========================================="
echo "System Monitor - $(date)"
echo "========================================="
echo ""
# Show system information
echo "CPU Usage:"
top -bn1 | grep "Cpu(s)" | awk '{print " " $2 " user, " $4 " system, " $8 " idle"}'
echo ""
echo "Memory Usage:"
free -h | grep Mem | awk '{print " Total: " $2 ", Used: " $3 ", Free: " $4}'
echo ""
echo "Disk Usage:"
df -h / | tail -1 | awk '{print " " $5 " used (" $3 " / " $2 ")"}'
echo ""
echo "Active Users:"
who | wc -l | awk '{print " " $1 " user(s) logged in"}'
echo ""
echo "Press Ctrl+C to exit..."
# Wait 5 seconds before next update
sleep 5
done
clear is called at the beginning of each loop iteration. This creates a dashboard effect where the screen is cleared and fresh statistics are displayed every 5 seconds. The user sees updated information in the same screen position, making it easy to track changes over time.
Clear Before Sensitive Operations
Clear the screen before displaying sensitive information to prevent shoulder surfing.
#!/bin/bash
# Secure password change script
# Clear screen before asking for passwords
clear
echo "Password Change Utility"
echo "========================"
echo ""
echo "WARNING: Ensure no one is watching your screen!"
echo ""
# Prompt for current password
read -sp "Enter current password: " CURRENT_PASS
echo ""
# Prompt for new password
read -sp "Enter new password: " NEW_PASS
echo ""
# Prompt for confirmation
read -sp "Confirm new password: " CONFIRM_PASS
echo ""
echo ""
# Process password change
if [ "$NEW_PASS" = "$CONFIRM_PASS" ]; then
echo "Changing password..."
# Password change logic here
sleep 2
echo "Password changed successfully!"
else
echo "Error: Passwords do not match!"
fi
# Clear screen again after operation
sleep 3
clear
echo "Password change session ended."
Clear with Command Chaining
Combine clear with other commands using shell operators for efficient workflows.
# Clear screen, then show directory listing
clear && ls -lh
# Clear screen, then display file content
clear && cat important_file.txt
# Clear screen, show calendar, wait, then clear again
clear && cal && sleep 5 && clear
# Clear and run command in one alias
alias cls='clear && ls -la'
# Use in command sequences
clear && echo "Starting backup..." && ./backup.sh && echo "Complete!"
# Clear before and after a command
clear && df -h && read -p "Press Enter to clear..." && clear
&& operator chains commands so they run sequentially only if the previous command succeeds. Clear always succeeds (returns exit status 0), so it works perfectly in chains. This lets you clear the screen and immediately run another command without needing separate lines or scripts.
# Add to ~/.bashrc
alias cls='clear && ls'
alias cll='clear && ls -la'
alias clt='clear && ls -lt | head -20'
alias cps='clear && ps aux'
Interactive Menu System with Clear
Create professional-looking menu-driven scripts using clear for navigation.
#!/bin/bash
# System administration menu
show_menu() {
clear
echo "========================================="
echo " System Administration Menu"
echo "========================================="
echo ""
echo "1. Show System Information"
echo "2. Display Disk Usage"
echo "3. Show Active Users"
echo "4. Check Network Status"
echo "5. View System Logs"
echo "6. Exit"
echo ""
echo -n "Enter your choice [1-6]: "
}
show_system_info() {
clear
echo "=== System Information ==="
echo ""
uname -a
echo ""
uptime
echo ""
read -p "Press Enter to return to menu..."
}
show_disk_usage() {
clear
echo "=== Disk Usage ==="
echo ""
df -h
echo ""
read -p "Press Enter to return to menu..."
}
# Main loop
while true; do
show_menu
read choice
case $choice in
1) show_system_info ;;
2) show_disk_usage ;;
3) clear && who && read -p "Press Enter..." ;;
4) clear && netstat -tuln && read -p "Press Enter..." ;;
5) clear && tail -20 /var/log/messages && read -p "Press Enter..." ;;
6) clear && echo "Goodbye!" && exit 0 ;;
*) clear && echo "Invalid option!" && sleep 2 ;;
esac
done
clear extensively to create a clean, professional interface. Each menu selection clears the screen before showing new information, and pressing Enter returns to a freshly-cleared menu. This creates a smooth, application-like experience in the terminal.
Clear vs Reset - Understanding the Difference
Clear and reset are different commands with different purposes.
# Clear command - just clears the screen
$ clear
# Screen is cleared, terminal settings unchanged
# Scrollback buffer usually preserved
# Reset command - reinitializes the terminal
$ reset
# Terminal is completely reinitialized
# All settings restored to defaults
# Screen is cleared
# Scrollback buffer may be cleared
# Takes longer to execute
- clear: Fast, simple screen clearing. Just removes visible text. Terminal settings unchanged.
- reset: Full terminal reinitialization. Restores default settings, clears screen, fixes garbled displays. Slower but more thorough.
- clear: Normal screen cleaning during regular work
- reset: When terminal is garbled (after catting a binary file), colors are wrong, or display is corrupted
# Example: Terminal is garbled after viewing binary file
$ cat /bin/ls
[garbled output, terminal looks broken]
# clear won't help - it's just clearing the screen
$ clear
[Screen clears but terminal still garbled]
# reset fixes it completely
$ reset
[Terminal fully restored to normal]
reset and press Enter. Even though you can't see it, it will fix your terminal!
Clear in Different Shells and Contexts
Understanding how clear works in various shells and terminal environments.
# In bash shell (most common)
$ clear
# In zsh shell
$ clear
# In sh shell
$ clear
# In csh/tcsh shell
$ clear
# Within screen session
$ clear
# Clears current screen window
# Within tmux session
$ clear
# Clears current tmux pane
# Over SSH connection
$ clear
# Works normally, depends on TERM variable
# In vim command mode
:!clear
# Executes clear command from vim
# In less/more pager
# Press Ctrl+L to refresh display (similar effect)
clear command works consistently across different shells because it's a standalone program (typically /usr/bin/clear) that uses the terminfo database. It works in screen and tmux by clearing the current window/pane. Over SSH, it depends on your terminal type being properly detected (TERM variable).
# Check your terminal type
$ echo $TERM
xterm-256color
# If clear doesn't work, TERM might be wrong
$ TERM=xterm clear
# Or set it permanently
$ export TERM=xterm-256color
Programmatic Screen Clearing in Scripts
Different methods of clearing the screen programmatically with varying levels of control.
#!/bin/bash
# Different methods to clear the screen
# Method 1: Using clear command (most portable)
clear
# Method 2: Using ANSI escape sequences directly
printf "\033[2J\033[H"
# Method 3: Using tput (more portable, uses terminfo)
tput clear
# Method 4: Multiple newlines (crude but always works)
printf '\n%.0s' {1..100}
# Method 5: Using escape sequence for scrollback clearing (some terminals)
printf "\033[3J\033[H\033[2J"
# Example: Function that clears screen with confirmation
clear_screen_safe() {
if [ -t 1 ]; then # Check if output is a terminal
if command -v clear &> /dev/null; then
clear
else
printf "\033[2J\033[H"
fi
fi
}
# Example: Clear with delay for readability
clear_with_delay() {
echo "Clearing screen in 3 seconds..."
sleep 3
clear
}
# Example: Conditional clear (only if terminal is tall enough)
smart_clear() {
LINES=$(tput lines)
if [ "$LINES" -gt 24 ]; then
clear
else
echo "---" # Just print separator for small terminals
fi
}
- clear: Most portable, uses terminfo database
- printf escape: Fast, works on most modern terminals
- tput clear: Very portable, uses terminfo like clear
- Multiple newlines: Crude but guaranteed to work
tput clear or test for the existence of clear command before calling it.
Clear in Complex Monitoring Scripts
Advanced example showing clear used in a production-style monitoring dashboard.
#!/bin/bash
# Advanced system dashboard with multiple panels
# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to get system metrics
get_cpu_usage() {
top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1
}
get_memory_usage() {
free | grep Mem | awk '{printf("%.1f"), $3/$2 * 100}'
}
get_disk_usage() {
df -h / | tail -1 | awk '{print $5}' | cut -d'%' -f1
}
get_load_average() {
uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | cut -d',' -f1
}
# Function to determine status color
status_color() {
local value=$1
local warning=$2
local critical=$3
if (( $(echo "$value > $critical" | bc -l) )); then
echo "$RED"
elif (( $(echo "$value > $warning" | bc -l) )); then
echo "$YELLOW"
else
echo "$GREEN"
fi
}
# Main dashboard display
show_dashboard() {
# Get metrics
CPU=$(get_cpu_usage)
MEM=$(get_memory_usage)
DISK=$(get_disk_usage)
LOAD=$(get_load_average)
# Determine status colors
CPU_COLOR=$(status_color "$CPU" 70 90)
MEM_COLOR=$(status_color "$MEM" 80 95)
DISK_COLOR=$(status_color "$DISK" 80 95)
# Clear screen and display dashboard
clear
echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC} SYSTEM MONITORING DASHBOARD ${BLUE}║${NC}"
echo -e "${BLUE}╠════════════════════════════════════════════════════════╣${NC}"
echo -e "${BLUE}║${NC} Hostname: $(hostname -s) ${BLUE}║${NC}"
echo -e "${BLUE}║${NC} Time: $(date '+%Y-%m-%d %H:%M:%S') ${BLUE}║${NC}"
echo -e "${BLUE}╠════════════════════════════════════════════════════════╣${NC}"
echo -e "${BLUE}║${NC} ${BLUE}║${NC}"
printf "${BLUE}║${NC} CPU Usage: ${CPU_COLOR}%5.1f%%%${NC} ${BLUE}║${NC}\n" "$CPU"
printf "${BLUE}║${NC} Memory Usage: ${MEM_COLOR}%5.1f%%%${NC} ${BLUE}║${NC}\n" "$MEM"
printf "${BLUE}║${NC} Disk Usage: ${DISK_COLOR}%5.1f%%%${NC} ${BLUE}║${NC}\n" "$DISK"
printf "${BLUE}║${NC} Load Average: %.2f ${BLUE}║${NC}\n" "$LOAD"
echo -e "${BLUE}║${NC} ${BLUE}║${NC}"
echo -e "${BLUE}╠════════════════════════════════════════════════════════╣${NC}"
echo -e "${BLUE}║${NC} Active Connections: $(netstat -an | grep ESTABLISHED | wc -l | xargs printf "%-3d") ${BLUE}║${NC}"
echo -e "${BLUE}║${NC} Logged In Users: $(who | wc -l | xargs printf "%-3d") ${BLUE}║${NC}"
echo -e "${BLUE}║${NC} Running Processes: $(ps aux | wc -l | xargs printf "%-3d") ${BLUE}║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo ""
echo "Press Ctrl+C to exit | Refreshing every 5 seconds..."
}
# Trap Ctrl+C for clean exit
trap 'clear; echo "Dashboard stopped."; exit 0' INT
# Main loop
while true; do
show_dashboard
sleep 5
done
clear at the beginning of each refresh cycle to create a smoothly updating display. The script collects system metrics, applies color coding based on thresholds, and presents everything in a professional box-drawn interface. The clear command is essential for creating the illusion of a live-updating dashboard rather than scrolling output.
- Add support for multiple pages/tabs
- Include alert notifications when thresholds are exceeded
- Log anomalies to a file while displaying
- Add keyboard controls for zooming into specific metrics
- Export metrics to time-series database
Additional Information
| Command/Shortcut | Description |
|---|---|
| Ctrl+L | Keyboard shortcut to clear screen (faster than typing clear) |
| reset | Reinitialize terminal (more thorough than clear) |
| tput clear | Alternative method using terminfo database |
| printf "\033[2J\033[H" | ANSI escape sequence to clear screen directly |
| Ctrl+K | Clear from cursor to end of line (in readline) |
| Ctrl+U | Clear from cursor to beginning of line (in readline) |
- Reads the
TERMenvironment variable to determine terminal type - Consults the terminfo database (
/usr/share/terminfo/) for that terminal type - Retrieves the appropriate control sequences for clearing the screen
- Sends those sequences to stdout
- Terminal emulator interprets the sequences and clears the display
By default, clear does NOT clear your terminal's scrollback buffer. You can usually still scroll up to see previous output. To clear scrollback as well:
- GNOME Terminal: Edit → Preferences → Scrolling → Enable "Limit scrollback"
- xterm:
printf '\033[3J'after clear - tmux:
clear && tmux clear-history - screen:
Ctrl+AthenC(capital C) - Terminal menu: Most terminals have "Clear Scrollback" in their menu
The clear command is very fast (typically <1ms) because it just outputs escape sequences. However, in very tight loops, you might notice flickering. For high-frequency updates, consider using terminal control libraries like ncurses or use techniques like double-buffering.
- clear does nothing: TERM variable might be wrong or unset
- garbled output after clear: Use
resetinstead - clear in scripts doesn't work: Output might be redirected or not going to a terminal
- slow clear over slow connection: Expected; escape sequences must travel over the network
# Add to ~/.bashrc
# Quick clear and list
alias cls='clear && ls'
alias cla='clear && ls -la'
# Clear and show current directory
alias cpwd='clear && pwd && ls'
# Clear history and screen
alias clearall='history -c && clear'
# Function: Clear and display a message
clearecho() {
clear
echo "========================================="
echo "$1"
echo "========================================="
}
# Function: Clear with confirmation
clearconfirm() {
read -p "Clear screen? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
clear
fi
}
Quick Reference Card
| Task | Command/Shortcut |
|---|---|
| Clear screen (command) | clear |
| Clear screen (shortcut) | Ctrl+L |
| Clear and run command | clear && command |
| Reset terminal completely | reset |
| Clear using tput | tput clear |
| Clear with ANSI codes | printf "\033[2J\033[H" |
| Check terminal type | echo $TERM |
| Clear scrollback (varies) | Terminal menu or printf '\033[3J' |
| Clear in script | [ -t 1 ] && clear |
| Show clear version | clear -V |