Bash Command Reference
What is Bash?
Bash (Bourne Again Shell) is a command-line interpreter and scripting language used for: - System automation - File management - Process control - Task scheduling
Similar to Python but specialized for system operations and shell scripting.
Basic Command Syntax
command [options] [arguments]
Components:
- command: The operation to perform (e.g., ls, cd, mkdir)
- options: Flags that modify command behavior (prefixed with - or --)
- arguments: What the command acts on (files, directories, strings)
Option Formats
Single Dash (-) - Short Options
Single-letter flags that can be combined:
ls -l # Long listing format
ls -a # Show all files (including hidden)
ls -la # Combined: long format + all files
ls -lah # Long + all + human-readable sizes
Double Dash (--) - Long Options
Multi-character descriptive flags:
ls --all # Show all files
tar --exclude="*.log" # Exclude log files
grep --ignore-case "text" # Case-insensitive search
End of Options Marker (--)
Explicitly marks the end of options:
rm -- -filename.txt # Delete file named "-filename.txt"
grep -- "--help" file # Search for the literal string "--help"
Navigation Commands
Change Directory
pwd # Print working directory (show current location)
cd /path/to/directory # Go to specific directory
cd ~ # Go to home directory
cd # Go to home (same as ~)
cd .. # Go up one level
cd ../.. # Go up two levels
cd - # Go to previous directory
cd / # Go to root directory
Examples:
cd ~/Documents # Go to Documents in home
cd ../../projects # Go up 2 levels, then into projects
cd - # Toggle between last two directories
Listing Files and Directories
Basic Listing
ls # List files in current directory
ls /path/to/dir # List files in specific directory
Common Options
| Option | Description | Example |
|---|---|---|
-l |
Long listing format (permissions, owner, size, date) | ls -l |
-a |
Show all files (including hidden . files) |
ls -a |
-h |
Human-readable file sizes (KB, MB, GB) | ls -lh |
-t |
Sort by modification time (newest first) | ls -lt |
-r |
Reverse sort order | ls -lr |
-R |
List subdirectories recursively | ls -R |
-S |
Sort by file size (largest first) | ls -lS |
-1 |
List one file per line | ls -1 |
-d |
List directories themselves, not contents | ls -ld */ |
Practical Examples
# Detailed view with human-readable sizes
ls -lh
# All files including hidden, long format, human-readable
ls -lah
# Sort by modification time, newest first
ls -lt
# Sort by size, largest first
ls -lS
# Show only directories
ls -d */
# Recursive listing of all files
ls -R
# Combine: all files, long format, human-readable, sorted by time
ls -laht
Creating Files and Directories
Create Directories
# Create single directory
mkdir newdirectory
# Create nested directories
mkdir -p parent/child/grandchild
# Create multiple directories
mkdir dir1 dir2 dir3
# Create with specific permissions
mkdir -m 755 public_folder
Create Files
# Create empty file
touch filename.txt
# Create multiple files
touch file1.txt file2.txt file3.txt
# Update timestamp of existing file
touch existing_file.txt
Removing Files and Directories
Remove Files
# Remove single file
rm filename.txt
# Remove multiple files
rm file1.txt file2.txt
# Remove all .txt files
rm *.txt
Remove Directories
# Remove empty directory
rmdir emptydirectory
# Remove directory and all contents
rm -r directoryname
# Force remove without prompts
rm -rf directoryname
Options Explained
| Option | Description |
|---|---|
-r |
Recursive - delete directory and everything inside |
-i |
Interactive - ask before deleting each file |
-f |
Force - delete without asking, ignore nonexistent files |
-v |
Verbose - show files being removed |
Safety Examples
# Interactive deletion (safe)
rm -i important_file.txt
# Show what's being deleted
rm -v *.log
# Careful deletion with confirmation
rm -ri old_project/
# Dangerous: force delete everything (use with caution!)
rm -rf folder/ # ⚠️ No confirmation, permanent!
⚠️ Warning: rm -rf is irreversible. Always double-check before using!
Copying and Moving
Copy Files and Directories
# Copy file
cp sourcefile.txt destination.txt
# Copy to directory
cp file.txt /path/to/directory/
# Copy multiple files to directory
cp file1.txt file2.txt /destination/
# Copy directory and all contents
cp -r sourcedirectory/ destinationdirectory/
Copy Options
| Option | Description |
|---|---|
-r |
Recursive - copy directories |
-i |
Interactive - prompt before overwrite |
-v |
Verbose - show files being copied |
-u |
Update - copy only newer files |
-p |
Preserve file attributes (permissions, timestamps) |
Examples:
# Copy with confirmation before overwrite
cp -i source.txt destination.txt
# Copy entire directory
cp -r project/ backup_project/
# Copy preserving permissions and timestamps
cp -rp source/ destination/
Move and Rename
# Rename file
mv oldname.txt newname.txt
# Move file to directory
mv file.txt /path/to/directory/
# Move multiple files
mv file1.txt file2.txt /destination/
# Move and rename simultaneously
mv old_project/file.txt new_project/renamed_file.txt
# Move directory
mv old_directory/ new_location/
Examples:
# Rename with confirmation
mv -i old.txt new.txt
# Move with verbose output
mv -v *.txt documents/
# Move all files from one directory to another
mv source_dir/* destination_dir/
Viewing and Editing Files
View File Contents
# Display entire file
cat filename.txt
# Display with line numbers
cat -n filename.txt
# View file page by page (forward only)
more filename.txt
# View file with navigation (forward and backward)
less filename.txt
# Display first 10 lines
head filename.txt
# Display first 20 lines
head -n 20 filename.txt
# Display last 10 lines
tail filename.txt
# Display last 20 lines
tail -n 20 filename.txt
# Follow file updates in real-time (useful for logs)
tail -f logfile.txt
Edit Files
# Edit with nano (beginner-friendly)
nano filename.txt
# Edit with vim (advanced)
vim filename.txt
# Edit with vi (basic)
vi filename.txt
Nano shortcuts:
- Ctrl + O - Save
- Ctrl + X - Exit
- Ctrl + K - Cut line
- Ctrl + U - Paste
Searching
Search Inside Files (grep)
# Search for text in file
grep "search_term" filename.txt
# Case-insensitive search
grep -i "search_term" filename.txt
# Search recursively in directory
grep -r "search_term" /path/to/directory/
# Search and show line numbers
grep -n "search_term" filename.txt
# Search for whole word only
grep -w "word" filename.txt
# Invert match (show lines that DON'T match)
grep -v "exclude_this" filename.txt
# Count matching lines
grep -c "pattern" filename.txt
Grep Options
| Option | Description |
|---|---|
-i |
Ignore case (case-insensitive) |
-r |
Recursive search in directories |
-n |
Show line numbers |
-v |
Invert match (exclude matching lines) |
-w |
Match whole words only |
-c |
Count matching lines |
-l |
Show only filenames with matches |
-A 3 |
Show 3 lines after match |
-B 3 |
Show 3 lines before match |
-C 3 |
Show 3 lines before and after match |
Examples:
# Find all Python files containing "import"
grep -r "import" *.py
# Find TODO comments with line numbers
grep -n "TODO" src/*.js
# Find files containing "error" (case-insensitive)
grep -ril "error" logs/
# Search with context (3 lines before and after)
grep -C 3 "exception" app.log
Find Files (find)
# Find files by name
find /path -name "filename.txt"
# Find files by pattern
find . -name "*.txt"
# Find directories
find . -type d -name "dirname"
# Find files modified in last 7 days
find . -type f -mtime -7
# Find files larger than 100MB
find . -type f -size +100M
# Find and delete empty files
find . -type f -empty -delete
File Permissions
View Permissions
ls -l filename.txt
# Output: -rw-r--r-- 1 user group 1234 Jan 1 12:00 filename.txt
Permission format: -rw-r--r--
- First character: file type (- = file, d = directory)
- Next 9 characters: permissions in groups of 3
- Owner (user): rw- (read, write, no execute)
- Group: r-- (read only)
- Others: r-- (read only)
Change Permissions (chmod)
# Numeric method (octal)
chmod 755 script.sh # rwxr-xr-x
chmod 644 file.txt # rw-r--r--
chmod 600 private.key # rw-------
# Symbolic method
chmod +x script.sh # Add execute permission
chmod -w file.txt # Remove write permission
chmod u+x script.sh # User: add execute
chmod g-w file.txt # Group: remove write
chmod o-r secret.txt # Others: remove read
Common permission values:
- 755 - rwxr-xr-x - Executable files (owner can modify)
- 644 - rw-r--r-- - Regular files (owner can modify)
- 600 - rw------- - Private files (only owner can access)
- 777 - rwxrwxrwx - Dangerous! (everyone has full access)
Input/Output Redirection
Output Redirection
# Redirect output to file (overwrite)
command > output.txt
# Append output to file
command >> output.txt
# Redirect errors to file
command 2> errors.txt
# Redirect both output and errors
command > output.txt 2>&1
command &> output.txt # Shorter syntax
Input Redirection
# Read input from file
command < input.txt
# Pipe output to another command
cat file.txt | grep "pattern"
ls -l | grep ".txt"
Useful Tips and Shortcuts
Command History
history # Show command history
!123 # Run command #123 from history
!! # Run last command
!grep # Run last command starting with "grep"
Ctrl + R # Search command history (interactive)
Keyboard Shortcuts
| Shortcut | Action |
|---|---|
Ctrl + C |
Cancel current command |
Ctrl + D |
Exit shell (logout) |
Ctrl + L |
Clear screen (same as clear) |
Ctrl + A |
Move to beginning of line |
Ctrl + E |
Move to end of line |
Ctrl + U |
Delete from cursor to beginning |
Ctrl + K |
Delete from cursor to end |
Tab |
Auto-complete file/directory names |
↑ / ↓ |
Navigate command history |
Wildcards
* # Match any characters
? # Match single character
[abc] # Match a, b, or c
[0-9] # Match any digit
# Examples
ls *.txt # All .txt files
ls file?.txt # file1.txt, file2.txt, etc.
ls [abc]*.txt # Files starting with a, b, or c
Quick Reference
Navigation
pwd # Current directory
cd dir # Change directory
cd .. # Up one level
cd - # Previous directory
Files
ls -lah # List all files, detailed, human-readable
mkdir dir # Create directory
touch file # Create file
rm file # Remove file
rm -rf dir # Remove directory
cp src dst # Copy
mv old new # Move/rename
Search
grep "text" file # Search in file
grep -r "text" dir/ # Search in directory
find . -name "*.txt" # Find files
View
cat file # Display file
head file # First 10 lines
tail file # Last 10 lines
tail -f file # Follow file updates
less file # Page through file
Safety Tips
- Always double-check before using
rm -rf- it's irreversible! - Use
-iflag for confirmations when deleting/overwriting - Test commands with
echofirst to see what will happen - Make backups before bulk operations
- Use
lsbeforermto verify what you're deleting
# Safe practice: preview before deleting
ls *.log # Preview files
rm -i *.log # Delete with confirmation
Happy Bash scripting! 🐚💻