Linux File Operations Guide
File operations are the foundation of working with Linux systems. This comprehensive guide covers everything you need to know about creating, copying, moving, deleting, and renaming files and directories in Linux.
Overview: Essential File Operation Commands
Linux provides powerful command-line tools for managing files and directories efficiently.
Core Commands Summary
| Command | Purpose | Example |
|---|---|---|
touch |
Create empty files | touch newfile.txt |
mkdir |
Create directories | mkdir mydir |
cp |
Copy files/directories | cp file.txt backup.txt |
mv |
Move/rename files | mv old.txt new.txt |
rm |
Remove files/directories | rm file.txt |
rmdir |
Remove empty directories | rmdir emptydir |
Creating Files and Directories
Create Empty Files with touch
The touch command creates empty files or updates existing file timestamps.
# Create a single empty file
touch newfile.txt
# Create multiple files at once
touch file1.txt file2.txt file3.txt
# Create file with specific timestamp
touch -t 202301011200 oldfile.txt
# Update only access time
touch -a existing.txt
# Update only modification time
touch -m existing.txt
Create Files with Content
# Create file using redirection
echo "Hello World" > greeting.txt
# Create file using cat
cat > myfile.txt << EOF
Line 1
Line 2
Line 3
EOF
# Create file using printf
printf "Name: %s\nAge: %d\n" "John" 30 > person.txt
# Append to existing file
echo "New line" >> existing.txt
Create Directories with mkdir
# Create a single directory
mkdir myfolder
# Create multiple directories
mkdir dir1 dir2 dir3
# Create nested directories (parents)
mkdir -p parent/child/grandchild
# Create directory with specific permissions
mkdir -m 755 publicdir
# Create directory structure
mkdir -p project/{src,docs,tests}
# Verbose output
mkdir -v newdir
Advanced Directory Creation
# Create multiple nested structures
mkdir -p company/{hr,it/{dev,ops},sales}
# Create with date-based names
mkdir backup-$(date +%Y%m%d)
# Create and enter directory
mkdir myproject && cd myproject
# Create directory only if it doesn't exist
[ ! -d "mydir" ] && mkdir mydir
Copying Files and Directories
Basic File Copying with cp
# Copy single file
cp source.txt destination.txt
# Copy file to directory
cp document.pdf ~/Documents/
# Copy multiple files to directory
cp file1.txt file2.txt file3.txt /backup/
# Preserve file attributes (permissions, timestamps)
cp -p original.txt copy.txt
# Verbose output
cp -v source.txt dest.txt
Interactive and Safe Copying
# Prompt before overwriting
cp -i file.txt existing.txt
# Don't overwrite existing files
cp -n file.txt backup.txt
# Update only if source is newer
cp -u old.txt new.txt
# Force overwrite without prompting
cp -f source.txt dest.txt
Copy Directories
# Copy directory recursively
cp -r source_dir/ destination_dir/
# Copy directory with all attributes
cp -a source_dir/ backup_dir/
# Copy directory verbosely
cp -rv myproject/ /backup/
# Copy only specific files from directory
cp source_dir/*.txt dest_dir/
Advanced Copy Operations
# Create backup of existing files
cp --backup=numbered file.txt dest.txt
# Copy and preserve directory structure
cp --parents src/config/app.conf /backup/
# Copy symlinks as symlinks (not files)
cp -P symlink /backup/
# Copy with progress (using rsync)
rsync -ah --progress source.txt dest.txt
# Copy only if destination is older or doesn't exist
cp -u *.txt /backup/
Copy with Filters
# Copy all .txt files
cp *.txt /backup/
# Copy files modified today
find . -name "*.log" -mtime 0 -exec cp {} /backup/ \;
# Copy large files only
find . -size +100M -exec cp {} /archive/ \;
# Copy and rename with pattern
for file in *.txt; do cp "$file" "backup_$file"; done
Moving and Renaming Files
Basic Move Operations with mv
# Move file to directory
mv file.txt /home/user/documents/
# Move multiple files
mv file1.txt file2.txt file3.txt /destination/
# Move all files of type
mv *.pdf ~/Documents/
# Move with verbose output
mv -v source.txt /destination/
Rename Files and Directories
# Rename a file
mv oldname.txt newname.txt
# Rename a directory
mv old_folder new_folder
# Rename with timestamp
mv report.txt report_$(date +%Y%m%d).txt
# Add extension
mv filename filename.txt
# Change extension
mv document.md document.txt
Interactive and Safe Moving
# Prompt before overwriting
mv -i file.txt existing.txt
# Don't overwrite existing files
mv -n source.txt dest.txt
# Update only if source is newer
mv -u old.txt new.txt
# Force move without prompting
mv -f source.txt dest.txt
# Create backup before overwriting
mv -b file.txt existing.txt
Batch Rename Files
# Rename all .txt to .md
for file in *.txt; do mv "$file" "${file%.txt}.md"; done
# Add prefix to files
for file in *.jpg; do mv "$file" "photo_$file"; done
# Add suffix before extension
for file in *.txt; do mv "$file" "${file%.txt}_backup.txt"; done
# Remove spaces from filenames
for file in *\ *; do mv "$file" "${file// /_}"; done
# Lowercase all filenames
for file in *; do mv "$file" "$(echo $file | tr '[:upper:]' '[:lower:]')"; done
# Using rename command (if available)
rename 's/\.txt$/.md/' *.txt
rename 's/ /_/g' *
Move Directory Contents
# Move all contents to parent directory
mv subfolder/* .
# Move all hidden files
mv source/.[!.]* destination/
# Move directory tree
mv -v source_dir/ /new/location/
# Merge directories
mv source/* destination/
Deleting Files and Directories
Remove Files with rm
# Delete single file
rm file.txt
# Delete multiple files
rm file1.txt file2.txt file3.txt
# Delete with verbose output
rm -v oldfile.txt
# Prompt before delete
rm -i important.txt
# Force delete without prompting
rm -f file.txt
Remove Directories
# Remove empty directory
rmdir emptydir
# Remove directory and contents recursively
rm -r directory/
# Force remove directory without prompts
rm -rf directory/
# Remove with confirmation
rm -ri directory/
# Remove directory verbosely
rm -rv oldproject/
Safe Deletion Practices
# Prompt for files with specific pattern
rm -i *.txt
# Preview before deletion (dry run)
find . -name "*.tmp" -print # Check first
find . -name "*.tmp" -delete # Then delete
# Move to trash instead of delete
mv unwanted.txt ~/.trash/
# Delete with confirmation for 3+ files
rm -I *.log
# Protected deletion
alias rm='rm -i'
Delete by Pattern
# Delete all .tmp files
rm *.tmp
# Delete all .log files recursively
find . -name "*.log" -delete
# Delete files older than 30 days
find /tmp -type f -mtime +30 -delete
# Delete empty files
find . -type f -empty -delete
# Delete files larger than 100MB
find . -type f -size +100M -delete
# Delete all except specific files
rm !(important.txt|keep.log)
Delete by Criteria
# Delete old backup files
find /backup -name "*.bak" -mtime +90 -delete
# Delete files by size
find . -type f -size +1G -exec rm -i {} \;
# Delete broken symbolic links
find . -type l ! -exec test -e {} \; -delete
# Clean temporary directories
rm -rf /tmp/*
# Delete compilation artifacts
rm -f *.o *.class *.pyc
Advanced File Operations
Copy with Progress Bar
# Using rsync
rsync -ah --progress source.txt destination.txt
# Using pv (pipe viewer)
pv source.txt > destination.txt
# Copy large directory with progress
rsync -ah --progress source_dir/ dest_dir/
Batch Operations
# Copy all PDFs from subdirectories
find . -name "*.pdf" -exec cp {} /collection/ \;
# Move files modified today
find . -type f -mtime 0 -exec mv {} /today/ \;
# Rename all files by adding date
find . -type f -exec sh -c 'mv "$1" "${1%.*}_$(date +%Y%m%d).${1##*.}"' _ {} \;
Working with Wildcards
# Copy all .txt and .md files
cp *.{txt,md} /backup/
# Move files starting with "test"
mv test* /archive/
# Delete files matching pattern
rm report_202[0-3]*.pdf
# Copy files with single character wildcard
cp file?.txt /backup/
# Advanced pattern matching (with extglob)
shopt -s extglob
rm !(file1|file2).txt # Delete all .txt except file1 and file2
Preserving Attributes
# Preserve all attributes when copying
cp -a source.txt destination.txt
# Preserve specific attributes
cp --preserve=mode,ownership,timestamps source.txt dest.txt
# Copy and preserve ACLs
cp --preserve=all source.txt dest.txt
# Copy with original permissions
cp -p file.txt backup.txt
File Operations with Spaces
# Handle filenames with spaces
cp "my file.txt" "backup file.txt"
# Use quotes in loops
for file in *.txt; do mv "$file" "prefix_$file"; done
# Delete files with spaces
rm "file with spaces.txt"
# Find and copy with null delimiter
find . -name "* *" -print0 | xargs -0 -I {} cp {} /backup/
Common Use Cases and Examples
Web Development
# Copy project for backup
cp -r myproject/ myproject_backup_$(date +%Y%m%d)/
# Clean build artifacts
rm -rf node_modules/ dist/ build/
# Copy configuration files
cp config/*.conf /etc/myapp/
# Rename environment configs
mv .env.example .env
System Administration
# Backup configuration
cp -p /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
# Archive old logs
mv /var/log/*.log.1 /archive/logs/
# Clean temp files
rm -rf /tmp/* /var/tmp/*
# Create directory structure for new user
mkdir -p /home/newuser/{documents,downloads,pictures}
Data Management
# Organize files by extension
mkdir -p sorted/{images,documents,videos}
mv *.{jpg,png,gif} sorted/images/
mv *.{pdf,doc,txt} sorted/documents/
mv *.{mp4,avi,mkv} sorted/videos/
# Archive old data
mv data_2023* /archive/
# Consolidate duplicate directories
cp -r source1/* destination/ && rm -rf source1/
Development Workflow
# Create project structure
mkdir -p myapp/{src,tests,docs,config}
# Copy template files
cp -r template/* newproject/
# Clean compilation artifacts
find . -name "*.pyc" -delete
find . -name "__pycache__" -type d -exec rm -rf {} +
# Backup before major changes
cp -r project/ project.backup/
Best Practices and Tips
Safety Tips
# Always use -i for important deletions
alias rm='rm -i'
alias mv='mv -i'
alias cp='cp -i'
# Test with ls or echo first
ls *.log # Verify files before deletion
rm *.log # Then delete
# Use trash directory instead of rm
mkdir -p ~/.trash
mv unwanted.txt ~/.trash/
# Create backups before risky operations
cp important.conf important.conf.bak
Performance Tips
# Use mv instead of cp+rm (faster for same filesystem)
mv file.txt /destination/ # Fast
cp file.txt /destination/ && rm file.txt # Slower
# Use rsync for large directories
rsync -a source/ dest/ # Better than cp -r
# Parallel copy operations
find . -name "*.jpg" -print0 | xargs -0 -P 4 -I {} cp {} /backup/
Efficiency Tips
# Create multiple directories at once
mkdir -p project/{src/{models,views,controllers},tests,docs}
# Use brace expansion
cp file.txt{,.bak} # Creates file.txt.bak
# Batch rename efficiently
rename 's/old/new/' *.txt
# Move and create destination
mkdir -p /new/path && mv files* /new/path/
Troubleshooting Common Issues
Permission Denied
# Use sudo for system files
sudo cp file.txt /etc/
# Check and fix permissions
ls -l file.txt
chmod 644 file.txt
# Change ownership
sudo chown user:group file.txt
Cannot Remove Directory Not Empty
# Use recursive deletion
rm -r directory/
# Or remove contents first
rm -rf directory/*
rmdir directory/
File Exists Error
# Force overwrite
cp -f source.txt dest.txt
# Or remove destination first
rm dest.txt && cp source.txt dest.txt
# Use backup option
cp --backup=numbered source.txt dest.txt
No Space Left on Device
# Check disk usage
df -h
# Find and remove large files
find . -type f -size +100M -exec ls -lh {} \;
# Clean temporary files
sudo rm -rf /tmp/* /var/tmp/*
Quick Reference
Most Common Operations
# Create file
touch newfile.txt
# Create directory
mkdir newfolder
# Copy file
cp source.txt backup.txt
# Copy directory
cp -r sourcedir/ backupdir/
# Move/rename
mv oldname.txt newname.txt
# Delete file
rm file.txt
# Delete directory
rm -rf directory/
Options Reference
| Option | Command | Description |
|---|---|---|
-r |
cp, rm | Recursive (for directories) |
-i |
cp, mv, rm | Interactive (prompt before overwrite) |
-f |
cp, mv, rm | Force (no prompts) |
-v |
cp, mv, rm | Verbose output |
-p |
cp | Preserve attributes |
-a |
cp | Archive mode (preserve all) |
-n |
cp, mv | No clobber (don't overwrite) |
-u |
cp, mv | Update (copy only if newer) |
-b |
cp, mv | Create backup of existing files |