Bash Reference & Cheatsheet — Quick Command Syntax Guide
Learning Path
flowchart LR
A["Bash Overview"] --> B["Core Concepts"]
B --> C["Intermediate Topics"]
C --> D["Advanced Topics"]
D --> E["Practical Applications"]
A --> F["You Are Here"]
style F fill:#f90,color:#fff
Bash is the default shell on most Linux distributions. This reference covers the most useful commands, syntax, and operators for everyday use and scripting.
What You’ll Find Here
- Basic syntax, variables, arrays, and arithmetic
- String, numeric, and file test operators
- Redirection, pipes, and process substitution
- Job control, conditionals, loops, and functions
- Common one-liners and exit codes
Basic Syntax
command [options] [arguments]
# Comments start with #
; # Command separator (run multiple on one line)
&& # Run next only if previous succeeds
|| # Run next only if previous fails
& # Run in background
\ # Line continuationVariables
name="Alice" # Assignment (no spaces around =)
echo "$name" # Dereference with $
readonly name # Make read-only
unset name # Delete variable
${name:-default} # Default value if unset
${name:?error msg} # Exit with error if unset/null
${#name} # String length
${name:0:3} # Substring: first 3 characters
${name/old/new} # Replace first match
${name//old/new} # Replace all matches
${name^} # Uppercase first character
${name^^} # Uppercase all charactersSpecial Variables
| Variable | Meaning |
|---|---|
$0 | Script name |
$1-$9 | Positional arguments 1-9 |
${10} | Positional argument 10+ (braces required) |
$# | Number of arguments |
$@ | All arguments (separate words) |
$* | All arguments (single string) |
$? | Exit code of last command |
$$ | Current script PID |
$! | Last background process PID |
$- | Current shell flags |
Arrays
# Indexed arrays
arr=("a" "b" "c")
echo "${arr[0]}" # "a" — first element
echo "${arr[@]}" # All elements
echo "${#arr[@]}" # Array length
arr+=("d") # Append element
# Associative arrays (declare first)
declare -A map
map[key]="value"
echo "${map[key]}"Arithmetic
$(( 5 + 3 )) # Arithmetic expansion
$(( 2 ** 10 )) # Power (1024)
(( i++ )) # Increment (in condition context)
let x=5+3 # let command| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division (integer) |
% | Modulo (remainder) |
** | Exponentiation |
String Comparison
| Operator | True When |
|---|---|
= or == | Strings equal (inside [[ ]]) |
!= | Strings not equal |
< | Less than (lexicographic) |
> | Greater than (lexicographic) |
-z | String is empty (zero length) |
-n | String is not empty |
Numeric Comparison
| Operator | True When |
|---|---|
-eq | Equal |
-ne | Not equal |
-lt | Less than |
-le | Less or equal |
-gt | Greater than |
-ge | Greater or equal |
File Tests
| Operator | True When |
|---|---|
-e | File exists |
-f | Regular file exists |
-d | Directory exists |
-s | File exists and is not empty |
-r | File is readable |
-w | File is writable |
-x | File is executable |
-L | File is a symbolic link |
-nt | File is newer than (file1 -nt file2) |
-ot | File is older than (file1 -ot file2) |
Redirection
> file # stdout to file (overwrite)
>> file # stdout to file (append)
2> file # stderr to file
2>&1 # stderr to stdout
&> file # Both stdout and stderr
< file # stdin from file
<< EOF # Heredoc (inline stdin)
line1
line2
EOF
<<< "string" # Here-string
> /dev/null # Discard outputPipes
cmd1 | cmd2 # Pipe stdout of cmd1 to stdin of cmd2
cmd1 |& cmd2 # Pipe both stdout and stderr
tee output.txt # Write to file AND stdoutProcess Substitution
diff <(ls dir1) <(ls dir2) # Compare outputs as files
while read line; do ...; done < <(command)Job Control
command & # Run in background
Ctrl+Z # Suspend foreground job
jobs # List background jobs
fg %1 # Bring job 1 to foreground
bg %1 # Continue job 1 in background
kill %1 # Kill job 1
nohup command & # Keep running after logout
disown # Remove job from shell's job tableConditionals
# if/then/elif/else
if [[ condition ]]; then
commands
elif [[ condition ]]; then
commands
else
commands
fi
# Single-line test
[[ -f "$file" ]] && echo "exists" || echo "not found"Logical Operators
| Operator | In [ ] | In [[ ]] |
|---|---|---|
| AND | -a | && |
| OR | -o | ` |
| NOT | ! | ! |
| Grouping | \( \) | ( ) |
Loops
# For — iterate over values
for i in {1..5}; do echo "$i"; done
# For — C-style
for (( i=0; i<10; i++ )); do echo "$i"; done
# For — iterate over files
for f in *.txt; do echo "Processing $f"; done
# While — loop while condition is true
while [[ condition ]]; do
commands
done
# While — read file line by line
while IFS= read -r line; do echo "$line"; done < file.txt
# Until — loop until condition becomes true
until ping -c1 google.com &>/dev/null; do
sleep 1
doneFunctions
# Definition
myfunc() {
local var="local" # Local scope (best practice)
echo "$1" # First argument
return 0 # Exit code (0 = success)
}
# Alternative syntax
function myfunc {
commands
}
# Call
myfunc "argument"Exit Codes
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of shell builtins |
| 126 | Command not executable |
| 127 | Command not found |
| 128 | Invalid exit argument |
| 130 | Terminated by Ctrl+C (SIGINT) |
| 137 | Killed by SIGKILL (-9) |
| 139 | Segmentation fault (SIGSEGV) |
Common One-Liners
# Find files containing text
grep -r "pattern" /path/
# Replace string in multiple files
sed -i 's/old/new/g' *.txt
# Count lines in files
wc -l *.csv
# Disk usage by directory (top 10)
du -sh * | sort -rh | head -10
# Processes using most memory
ps aux --sort=-%mem | head -10
# Kill all processes matching a name
pkill -f "node app.js"
# Watch a command every 2 seconds
watch -n 2 'df -h'
# Run a command with a timeout
timeout 10 curl https://example.com
# Find large files (>100MB)
find / -type f -size +100M -exec ls -lh {} \;
# Monitor log file in real-time
tail -f /var/log/syslog
# Create a timestamped backup
tar czf "backup-$(date +%Y%m%d_%H%M%S).tar.gz" /path/to/data
# Generate a random password
openssl rand -base64 16
# Get your public IP
curl -s https://api.ipify.org
# HTTP status code check
curl -s -o /dev/null -w "%{http_code}" https://example.comCommon Aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias ..='cd ..'
alias ...='cd ../..'
alias grep='grep --color=auto'
alias df='df -h'
alias free='free -h'Common Mistakes Beginners Make
1. Skipping the Fundamentals
Many beginners jump straight to advanced topics without mastering the basics. Take time to understand the core concepts before moving on.
2. Not Practicing Enough
Reading tutorials without writing code leads to shallow understanding. Code along with every example and experiment on your own.
3. Ignoring Error Messages
Error messages tell you exactly what went wrong. Read them carefully — they usually point to the line and type of issue.
4. Copy-Pasting Without Understanding
It’s tempting to copy code from tutorials, but typing it yourself and understanding each line builds real skill.
5. Giving Up Too Early
Every developer hits frustrating bugs. Take breaks, ask for help, and remember that struggling is part of learning.
Practice Questions
What does
${name:-default}do? Returns “default” if$nameis unset or null, otherwise returns the value of$name.What is the difference between
$@and$*?$@preserves argument boundaries as separate words.$*joins them into one string.What does
2>&1mean? Redirect file descriptor 2 (stderr) to file descriptor 1 (stdout).What does
set -edo? Exit immediately if a command exits with a non-zero status.What exit code indicates success? 0. Any non-zero exit code indicates an error.
Challenge: Without looking at this reference, write a one-liner that finds all .log files in /var/log, counts how many lines each contains, sorts by line count descending, and shows the top 5.
FAQ
Try It Yourself
Open your terminal and run through these to test your understanding:
# Variable expansion
name="Alice"
echo "${name:0:2}" # "Al"
echo "${name^^}" # "ALICE"
# Arithmetic
echo $(( (5 + 3) * 2 )) # 16
# String comparison
[[ "hello" == "hello" ]] && echo "match"
# File test
[[ -d /tmp ]] && echo "/tmp exists"
# Process substitution
diff <(echo "a") <(echo "b")What’s Next
| Reference | What It Covers |
|---|---|
| Bash Basics | Beginner tutorial for the Bash command line |
| Shell Scripts | Writing reusable automation scripts |
| Linux Command Reference | System administration commands, services, package management |
What’s Next
Congratulations on completing this Bash Reference tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro