Bash Cheatsheet
Bash
Shell
Terminal
Scripting
Complete reference for Bash shell commands, shortcuts, scripting techniques, and advanced terminal operations for efficient command-line usage.
Quick Reference
⌨️ Shortcuts & History
Essential keyboard shortcuts and command history
📁 File Operations
File and directory management commands
🔧 Variables & Functions
Shell scripting and variable manipulation
🔄 Process Control
Job management and process handling
Shortcuts and History
Master these keyboard shortcuts to dramatically improve your command-line efficiency and navigation speed.
Navigation Shortcuts
Move to beginning of line
Move to end of line
Move backward one character
Move forward one character
Move backward one word
Move forward one word
Editing Shortcuts
Delete to end of line
Delete to beginning of line
Delete word behind cursor
Delete next word
Transpose two characters
Transpose two words
Control Shortcuts
Halt current command
Log out or delete character
Clear screen
Suspend current command
History Navigation
Previous command in history
Next command in history
Search backward in history
Repeat last command
Refer to command line 'n'
Refer to command starting with 'string'
Show command history
Advanced Shortcuts
Capitalize word from cursor
Lowercase word from cursor
Uppercase word from cursor
Paste last word from previous command
Start recording keyboard macro
Stop recording keyboard macro
Execute recorded macro
Bash Basics
Environment Information
Display all environment variables
Show current shell
Show Bash version
Switch to Bash shell
Find Bash location
Find Bash executable path
Clear terminal screen
Exit current session
File Commands
File operations are fundamental to shell usage. These commands help you navigate, manipulate, and manage files efficiently.
File Listing and Information
List files in current directory
List files with detailed information
List all files including hidden
Show directory tree structure
Show file/directory sizes
Show disk usage
File Creation and Modification
Create or update file
Create temporary file
Create symbolic link
Show symbolic link target
File Content Operations
Display file content
Display file with line numbers
Show line numbers in file
Copy file content to another file
Append file content to another file
Show first part of file
Show first lines of file (default: 10)
Show last lines of file (default: 10)
Follow file changes in real-time
File Management
Move/rename file
Copy file
Remove file
Edit file with Vim
File Search and Analysis
Find files by name
Compare two files
Count lines, words, characters
Count only lines
Count only words
Count only characters
Sort file contents alphabetically
Sort numerically
Sort in reverse order
Sort by specific field
Reverse string characters
File Permissions and Compression
Change file permissions
Compress file with gzip
Decompress gzip file
View gzipped file without decompressing
Text Processing
Search for pattern in files
Search recursively in directory
Print nth line from file
Display lines from x to y
Replace pattern in file (output to stdout)
Replace pattern in file (in-place)
Replace pattern from input stream
Printing Operations
Print file
Check printer queue
Remove job from printer queue
Convert text to PostScript
Print DVI files
Directory Commands
Basic Directory Operations
Create new directory
Remove empty directory
Remove directory and contents
Rename directory
Copy directory recursively
Directory Navigation
Change to home directory
Change to parent directory
Change to specific directory
Change to home directory
Change to previous directory
Show current directory
SSH, System Info & Network Commands
System information and network commands are essential for server management and troubleshooting.
SSH Operations
Connect to host as user
Connect on specific port
Copy SSH key to host
User and System Information
Show current username
Switch to different user
Switch to root user
Execute command as root
Change password
Show disk quota
Show current date and time
Show month's calendar
Show system uptime
Show who's online
Show user information
Show kernel information
Show command manual
Show command documentation
Show built-in help
Show last logins
Process Management
List your processes
Kill process by PID
Kill all processes by name
Show active processes
List open files
List background jobs
Bring job to foreground
Bring specific job to foreground
Network Commands
Ping host
Get domain whois information
Get DNS information
Reverse DNS lookup
Download file
Show network connections
Measure command execution time
Variables
Variables in Bash are fundamental for storing data and creating dynamic scripts.
Basic Variable Operations
Define a variable
Define variable for subprocess
Check variable value
Print process ID of current shell
Print process ID of last background job
Display exit status of last command
Read input into variable
Read input with prompt
Display in columns
Perform mathematical calculation
Environment Variables
Export environment variable
Export function
Export and assign simultaneously
Copy Bash variable
Declare exported variable
Arrays
Define array elements
Alternative array definition
Another array definition method
Access array element
Get length of array element
Get number of array elements
Variable Declarations
Treat variables as arrays
Use function names only
Display function names without definitions
Treat variables as integers
Make variables read-only
Mark variables for export
Convert to lowercase
Make associative array
Parameter Expansion
Return value or default word
Return value or word (alternative)
Set variable if null and return
Return value or print error
Return word if variable exists
Extract substring
Remove shortest match from beginning
Remove longest match from beginning
Remove shortest match from end
Remove longest match from end
Replace first match
Replace all matches
Get variable length
Pattern Matching
Match zero or more occurrences
Match one or more occurrences
Match zero or one occurrence
Match exactly one pattern
Match anything except pattern
Command Substitution
Run command and return output
Make variable local
Functions
Functions allow you to group commands and create reusable code blocks in your scripts.
Function Definition
Define a function
Delete function definition
Display all defined functions
Flow Controls
Flow control structures allow you to create conditional logic and loops in your scripts.
Logical Operators
AND operator
OR operator
AND operator in test
OR operator in test
String Comparisons
String equality
String inequality
String less than (alphabetically)
String greater than (alphabetically)
String sorted after
String sorted before
String is not null
String is null
File Tests
File exists
File is directory
File exists (same as -a)
File is regular file
File is readable
File exists and not empty
File is writable
File is executable
File was modified since last read
You own the file
File group matches yours
File1 is newer than file2
File1 is older than file2
Numeric Comparisons
Less than
Less than or equal
Equal
Greater than or equal
Greater than
Not equal
Conditional Statements
If statement
Case statement
Loops
For loop with range
For loop with list
C-style for loop
Select menu
While loop
Until loop
Command-Line Processing
Command Lookup Override
Remove alias and function lookup
Look up only built-ins
Enable/disable shell built-ins
Re-evaluate arguments
Input/Output Redirectors
I/O redirection is powerful for controlling where command input comes from and where output goes.
Basic Redirection
Pipe output to input
Input from file
Output to file
Append to file
Force output to file
Use file for both input and output
File Descriptor Operations
Force output from descriptor n
Use file for both I/O on descriptor n
Direct descriptor n to file
Take descriptor n from file
Append descriptor n to file
Duplicate stdout to descriptor n
Duplicate stdin from descriptor n
Copy output descriptor
Copy input descriptor
Direct stdout and stderr to file
Close standard input
Close standard output
Close output from descriptor n
Close input from descriptor n
Output to terminal and file
Process Handling
Process management is crucial for controlling running programs and managing system resources.
Background Jobs
Run job in background
List all jobs
List jobs with PIDs
Bring job to foreground
Bring most recent background job
Bring second most recent job
Bring job number N
Bring job starting with string
Bring job containing string
Process Termination
List all signals
Terminate process by PID
Send specific signal
Send TERM signal
Kill job by number
Process Information
Show current processes
Show all processes with tty
Signal Handling
Execute command on signal
Ignore signals
Reset signal handling
Process Control
Remove process from job list
Wait for background jobs
Wait specified seconds
Display progress bar
Auto-respond yes
Debugging Shell Programs
Debugging tools help you identify and fix issues in your shell scripts.
Syntax Checking
Check syntax without running
Set no-execute option in script
Verbose Output
Echo commands before running
Set verbose option in script
Execution Tracing
Echo commands after processing
Set trace option in script
Debug Traps
Print variable on exit
Error trap function
Debug trap function
Turn off debug trap
Return trap function
Colors and Backgrounds
Color codes allow you to add visual formatting to your terminal output and scripts.
Reset Color
Text reset
Regular Colors
Basic colors
Additional colors
Bold Colors
Bold text colors
Underlined Colors
Underlined text colors
Background Colors
Background colors
Usage Examples
Print colored text
Printf with colors
Tips & Tricks
These advanced tips will help you become more productive with Bash and shell scripting.
Aliases
Set an alias in .bash_profile
Quick Directory Access
Set up cdable variables in .bashrc
Best Practices
Follow these Bash best practices for writing maintainable and efficient shell scripts.
- Use proper quoting to handle spaces and special characters in variables
- Check exit codes using
$?
to handle errors appropriately - Use functions to organize code and avoid repetition
- Add error handling with
set -e
to exit on errors - Use meaningful variable names and add comments for clarity
- Test scripts thoroughly before deploying to production
- Use shellcheck to validate script syntax and catch common issues
- Handle edge cases like empty inputs and missing files
Learn More
Explore comprehensive Bash documentation and advanced scripting techniques
Resources
Written by
Deepak Jangra
Created At
Wed Jan 15 2025
Updated At
Fri Jun 13 2025