Bash: Creating and Deleting Files
Creating and deleting files and directories is fundamental to working in Linux. Whether you're organizing reconnaissance data, managing exploits, or cleaning up after yourself, these commands are essential. This lesson covers everything from simple file creation to safe deletion practices.
What You'll Learn
- Creating files (touch, echo, cat, editors)
- Creating directories (mkdir)
- Deleting files (rm)
- Deleting directories (rmdir, rm -r)
- Safe deletion practices
- Recovering from mistakes
- Wildcards and bulk operations
Creating Files
1. touch - Create Empty File
Basic usage:
touch filename.txt
Creates an empty file if it doesn't exist.
Multiple files:
touch file1.txt file2.txt file3.txt
With paths:
touch /tmp/test.txt
touch ~/Documents/notes.txt
Update timestamp:
# If file exists, touch updates its modification time
touch existing_file.txt
Use cases in pentesting:
# Create placeholder files
touch targets.txt findings.txt report.txt
# Mark timestamp for later comparison
touch before_scan.marker
# ... run scan ...
# Find files modified after marker:
find . -newer before_scan.marker
2. echo - Create File with Content
Redirect output to file:
echo "Hello, World!" > file.txt
Append to file:
echo "Additional line" >> file.txt
Create multiline file:
echo -e "Line 1\nLine 2\nLine 3" > file.txt
Create file with variables:
TARGET="example.com"
echo "Scanning $TARGET" > scan_log.txt
Practical examples:
# Create wordlist
echo -e "admin\nroot\nuser\ntest" > users.txt
# Create IP list
echo -e "192.168.1.1\n192.168.1.2\n192.168.1.3" > targets.txt
# Log command output
echo "Scan started: $(date)" > scan.log
nmap target.com >> scan.log
3. cat - Create File Interactively
Create file (type until Ctrl+D):
cat > file.txt
Type your content here
Press Ctrl+D when done
Append to file:
cat >> file.txt
More content
Ctrl+D
Copy file:
cat source.txt > destination.txt
Combine files:
cat file1.txt file2.txt > combined.txt
4. Using Text Editors
nano (beginner-friendly):
nano filename.txt
# Ctrl+O to save
# Ctrl+X to exit
vim (powerful):
vim filename.txt
# Press 'i' to insert
# Type content
# Press Esc, then :wq to save and quit
vi (minimal):
vi filename.txt
Creating Directories
mkdir - Make Directory
Single directory:
mkdir mydir
Multiple directories:
mkdir dir1 dir2 dir3
Nested directories (create parents):
mkdir -p parent/child/grandchild
With permissions:
mkdir -m 755 mydir
# 755 = rwxr-xr-x
Practical examples:
# Organize pentesting engagement
mkdir -p engagement/recon engagement/exploit engagement/report
mkdir -p engagement/loot engagement/screenshots
# Create dated backup directory
mkdir backup-$(date +%Y-%m-%d)
# Create multiple target directories
mkdir -p targets/{company1,company2,company3}/{recon,scans,notes}
Deleting Files
rm - Remove Files
Delete single file:
rm file.txt
Delete multiple files:
rm file1.txt file2.txt file3.txt
Delete with confirmation (recommended!):
rm -i file.txt
# Prompts: rm: remove regular file 'file.txt'? y/n
Force delete (no confirmation):
rm -f file.txt
Delete all files in directory:
rm *
Delete specific file types:
rm *.txt
rm *.log
rm *.tmp
Deleting Directories
rmdir - Remove Empty Directory
Basic usage:
rmdir dirname
Only works if directory is empty!
rmdir nonempty_dir
# Error: rmdir: failed to remove 'nonempty_dir': Directory not empty
rm -r - Remove Directory and Contents
Recursive delete:
rm -r dirname
Deletes directory and everything inside.
With confirmation:
rm -ri dirname
# Prompts for each file
Force recursive delete:
rm -rf dirname
⚠️ DANGEROUS: No confirmation, no undo!
Wildcards and Patterns
* (Asterisk) - Match Any Characters
# Delete all .txt files
rm *.txt
# Delete all files starting with "test"
rm test*
# Delete all files ending with ".log"
rm *.log
? (Question Mark) - Match Single Character
# Delete file1.txt, file2.txt, but not file10.txt
rm file?.txt
# Delete test1, test2, test3, but not test10
rm test?
[] (Brackets) - Match Character Set
# Delete file1.txt through file5.txt
rm file[1-5].txt
# Delete filea.txt, fileb.txt, filec.txt
rm file[abc].txt
# Delete files with numbers
rm file[0-9].txt
Combining Wildcards
# Delete all .txt and .log files
rm *.txt *.log
# Delete files starting with "test" and ending with ".txt"
rm test*.txt
# Delete 2-character files
rm ??
Safe Deletion Practices
1. Always Check Before Deleting
# List files first
ls *.txt
# Then delete
rm *.txt
2. Use -i for Important Operations
# Interactive mode prompts for each file
rm -i *.txt
3. Use echo to Preview
# See what would be deleted
echo rm *.txt
# See expanded wildcard
echo *.txt
4. Move to Trash Instead
Create a trash function in ~/.bashrc:
trash() {
mkdir -p ~/.trash
mv "$@" ~/.trash/
}
# Usage:
trash file.txt
5. Create Aliases for Safety
Add to ~/.bashrc:
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
Dangerous Commands to Avoid
Never Run These!
# Delete everything in root!
rm -rf /
# Delete everything in current directory
rm -rf *
# Delete home directory
rm -rf ~
# Delete current directory
rm -rf .
# Delete system directories
rm -rf /etc
rm -rf /usr
rm -rf /var
Modern Linux Protection
# Most systems require --no-preserve-root
rm -rf / # Error: refusing to remove '/'
rm -rf / --no-preserve-root # Actually deletes (don't do this!)
Recovering from Mistakes
Files Are Gone Forever
Linux has NO RECYCLE BIN by default!
rm = PERMANENT deletion
No "undo" button!
Recovery Options
1. Backups:
# If you have backups, restore from there
2. File Recovery Tools:
# testdisk / photorec
sudo apt install testdisk
# extundelete (ext3/ext4)
sudo apt install extundelete
# Recovery is NOT guaranteed!
3. Prevention:
- Make backups regularly
- Use version control (git)
- Use confirmation flags (-i)
- Think before deleting!
Practical Scenarios
Scenario 1: Organizing a Pentest
# Create directory structure
mkdir -p pentest/{recon,scans,exploits,loot,reports}
# Create placeholder files
touch pentest/recon/targets.txt
touch pentest/recon/subdomains.txt
touch pentest/scans/nmap_results.txt
touch pentest/reports/findings.md
Scenario 2: Cleaning Up Temp Files
# Create temp directory
mkdir /tmp/my_scan
# Create temp files
touch /tmp/my_scan/{temp1,temp2,temp3}.txt
# Later, clean up
rm -rf /tmp/my_scan
Scenario 3: Bulk File Creation
# Create 10 numbered files
touch file{1..10}.txt
# Create files with dates
for i in {1..7}; do
touch "backup-$(date -d "$i days ago" +%Y-%m-%d).txt"
done
Scenario 4: Safe Deletion
# Check what will be deleted
ls *.log
# Preview deletion
echo rm *.log
# Delete with confirmation
rm -i *.log
Practical Exercises
Exercise 1: Create File Hierarchy
# Create this structure:
# project/
# ├── src/
# ├── tests/
# ├── docs/
# └── README.md
mkdir -p project/{src,tests,docs}
touch project/README.md
tree project
Exercise 2: Create and Delete
# Create 5 test files
touch test{1..5}.txt
# List them
ls test*.txt
# Delete odd-numbered files
rm test1.txt test3.txt test5.txt
# Verify
ls test*.txt
Exercise 3: Wildcard Practice
# Create variety of files
touch file1.txt file2.txt file10.txt
touch report.log scan.log
touch data.csv results.csv
# Delete only .txt files
rm *.txt
# Delete only single-digit numbered logs
rm file?.log
# Clean up
rm *
Exercise 4: Safe Deletion Script
# Create safe delete function
nano ~/.bashrc
# Add:
trash() {
mkdir -p ~/.trash
echo "Moving to trash: $@"
mv "$@" ~/.trash/
}
# Reload
source ~/.bashrc
# Test
touch testfile.txt
trash testfile.txt
ls ~/.trash/
Quick Reference
Creating Files:
touch file.txt # Empty file
echo "text" > file.txt # File with content
echo "text" >> file.txt # Append to file
cat > file.txt # Interactive (Ctrl+D to end)
nano file.txt # Text editor
Creating Directories:
mkdir dir # Single directory
mkdir dir1 dir2 dir3 # Multiple
mkdir -p parent/child # Nested (create parents)
mkdir -m 755 dir # With permissions
Deleting Files:
rm file.txt # Delete file
rm -i file.txt # Interactive (confirm)
rm -f file.txt # Force (no confirm)
rm *.txt # Wildcard
Deleting Directories:
rmdir dir # Empty directory only
rm -r dir # Directory and contents
rm -ri dir # Interactive recursive
rm -rf dir # Force recursive (DANGEROUS!)
Wildcards:
* # Match any characters
? # Match single character
[abc] # Match a, b, or c
[1-5] # Match 1 through 5
{file1,file2} # Brace expansion
Resources
Man Pages:
man touch
man mkdir
man rm
man rmdir
Online:
- Bash Guide: https://mywiki.wooledge.org/BashGuide
- Explain Shell: https://explainshell.com
Practice:
- OverTheWire: Bandit: https://overthewire.org/wargames/bandit/
- Your own Linux VM
Next Steps
- Practice creating files and directories
- Master wildcards for bulk operations
- Set up safety aliases (rm -i, mv -i, cp -i)
- Create a trash function instead of direct rm
- Always double-check before rm -rf!
Creating and deleting seems simple, but one wrong rm -rf can ruin your day. Practice safe habits from the beginning!
"rm -rf: Because sometimes you need to make very permanent decisions."