File Operations
Navigation
Directory Navigation
# Change directory
cd /path/to/directory
cd ~ # Home directory
cd - # Previous directory
cd .. # Parent directory
cd ../.. # Two levels up
# Print working directory
pwd
pwd -P # Physical path (resolve symlinks)
# Directory stack
pushd /path/to/dir # Push directory onto stack
popd # Pop directory from stack
dirs # Show directory stack
Listing Files
# Basic listing
ls
ls -l # Long format
ls -la # Include hidden files
ls -lh # Human-readable sizes
ls -lt # Sort by modification time
ls -lS # Sort by file size
# Recursive listing
ls -R
find . -type f # All files recursively
find . -type d # All directories recursively
# Tree view (if available)
tree
tree -a # Include hidden files
tree -d # Directories only
tree -L 2 # Limit depth to 2
File and Directory Operations
Creating Files and Directories
# Create empty file
touch file.txt
touch file1.txt file2.txt # Multiple files
# Create directory
mkdir directory
mkdir -p path/to/nested/dir # Create parent directories
# Create file with content
echo "Hello World" > file.txt
cat > file.txt << EOF
Line 1
Line 2
EOF
# Create temporary files
mktemp # Create temporary file
mktemp -d # Create temporary directory
mktemp -t prefix.XXXXXX # Create with template
Copying Files
# Copy file
cp source.txt dest.txt
cp source.txt /path/to/dest/
# Copy directory
cp -r source_dir dest_dir
# Copy with options
cp -i source dest # Interactive (prompt before overwrite)
cp -u source dest # Update (copy only if source is newer)
cp -v source dest # Verbose
cp -p source dest # Preserve attributes
# Copy multiple files
cp file1.txt file2.txt dest_dir/
cp *.txt dest_dir/
# Backup while copying
cp file.txt{,.bak} # Creates file.txt.bak
Moving and Renaming
# Move/rename file
mv oldname.txt newname.txt
mv file.txt /path/to/new/location/
# Move directory
mv old_dir new_dir
# Move with options
mv -i source dest # Interactive
mv -u source dest # Update only
mv -v source dest # Verbose
# Rename multiple files
for file in *.txt; do
mv "$file" "${file%.txt}.backup"
done
Removing Files
# Remove file
rm file.txt
rm -f file.txt # Force removal
rm -i file.txt # Interactive
# Remove directory
rmdir empty_dir # Remove empty directory
rm -r directory # Remove directory and contents
rm -rf directory # Force remove directory
# Safe removal with confirmation
rm -i *.txt
# Remove files older than N days
find . -name "*.log" -mtime +7 -delete
File Permissions
Understanding Permissions
# View permissions
ls -l file.txt
# Output: -rw-r--r-- 1 user group 1024 Jan 1 12:00 file.txt
# ||||||||| | | | | | | | |
# |owner|group|other|links|user|group|size|date|name
# |rwx |rwx |rwx |
# Permission bits
r = read (4)
w = write (2)
x = execute (1)
Changing Permissions
# Chmod with symbolic notation
chmod u+x file.txt # Add execute for user
chmod g-w file.txt # Remove write for group
chmod o=r file.txt # Set other to read only
chmod a+r file.txt # Add read for all
# Chmod with octal notation
chmod 755 file.txt # rwxr-xr-x
chmod 644 file.txt # rw-r--r--
chmod 600 file.txt # rw-------
# Recursive permissions
chmod -R 755 directory/
# Common permission patterns
chmod 755 script.sh # Executable script
chmod 644 document.txt # Regular file
chmod 600 private.key # Private key
chmod 700 ~/.ssh/ # SSH directory
Changing Ownership
# Change owner
chown user file.txt
chown user:group file.txt
# Recursive ownership
chown -R user:group directory/
# Change group only
chgrp group file.txt
# Copy ownership from another file
chown --reference=ref_file target_file
File Information
File Statistics
# File information
stat file.txt
file file.txt # File type
du -h file.txt # Disk usage
wc -l file.txt # Line count
wc -w file.txt # Word count
wc -c file.txt # Character count
# Directory size
du -sh directory/ # Human-readable directory size
du -h --max-depth=1 # Size of subdirectories
File Attributes
# Extended attributes (Linux)
getfattr -d file.txt
setfattr -n user.comment -v "My comment" file.txt
# Immutable attribute (Linux)
chattr +i file.txt # Make immutable
chattr -i file.txt # Remove immutable
lsattr file.txt # List attributes
Finding Files
Find Command
# Basic find
find . -name "*.txt"
find /path -name "filename"
# Find by type
find . -type f # Files only
find . -type d # Directories only
find . -type l # Symbolic links only
# Find by size
find . -size +100M # Larger than 100MB
find . -size -1k # Smaller than 1KB
find . -size 500c # Exactly 500 bytes
# Find by time
find . -mtime -7 # Modified in last 7 days
find . -atime +30 # Accessed more than 30 days ago
find . -ctime -1 # Changed in last 24 hours
# Find by permissions
find . -perm 644 # Exactly 644
find . -perm -644 # At least 644
find . -perm /644 # Any of 644 bits set
# Execute commands on found files
find . -name "*.txt" -exec cat {} \;
find . -name "*.log" -exec rm {} \;
find . -name "*.tmp" -delete
Locate Command
# Update locate database
updatedb
# Find files quickly
locate filename
locate "*.txt"
# Case-insensitive search
locate -i filename
Which and Whereis
# Find executable in PATH
which command
which -a command # All matches
# Find command, source, and manual
whereis command
Links
Symbolic Links
# Create symbolic link
ln -s /path/to/target linkname
ln -s ../file.txt symlink.txt
# Create relative symbolic link
ln -sr target linkname
# Read symbolic link
readlink linkname
readlink -f linkname # Follow all links
# Find broken links
find . -type l -! -exec test -e {} \; -print
Hard Links
# Create hard link
ln target hardlink
# Find hard links
find . -samefile original_file
find . -inum $(stat -c %i original_file)
# Count hard links
ls -l file.txt # Second column shows link count
Archive Operations
Tar Archives
# Create tar archive
tar -cf archive.tar file1 file2 directory/
tar -czf archive.tar.gz directory/ # With gzip compression
tar -cjf archive.tar.bz2 directory/ # With bzip2 compression
# Extract tar archive
tar -xf archive.tar
tar -xzf archive.tar.gz
tar -xjf archive.tar.bz2
# List archive contents
tar -tf archive.tar
tar -tzf archive.tar.gz
# Extract specific files
tar -xf archive.tar file1 file2
# Add files to existing archive
tar -rf archive.tar newfile.txt
Compression
# Gzip compression
gzip file.txt # Creates file.txt.gz
gunzip file.txt.gz # Extracts file.txt
gzip -k file.txt # Keep original file
# Bzip2 compression
bzip2 file.txt # Creates file.txt.bz2
bunzip2 file.txt.bz2 # Extracts file.txt
# Zip archives
zip -r archive.zip directory/
unzip archive.zip
unzip -l archive.zip # List contents
File Monitoring
Watching Files
# Monitor file changes
tail -f /var/log/syslog
tail -f -n 100 logfile.txt # Last 100 lines
# Watch command output
watch -n 2 'ls -la' # Run command every 2 seconds
watch -d 'df -h' # Highlight differences
# Monitor file modifications
inotifywait -m /path/to/file # Requires inotify-tools
File Comparison
# Compare files
diff file1.txt file2.txt
diff -u file1.txt file2.txt # Unified format
diff -c file1.txt file2.txt # Context format
# Compare directories
diff -r dir1/ dir2/
# Other comparison tools
cmp file1.txt file2.txt # Binary comparison
comm file1.txt file2.txt # Line-by-line comparison
Advanced File Operations
File Descriptors
# Redirect to file descriptor
exec 3> output.txt
echo "Hello" >&3
exec 3>&- # Close file descriptor
# Read from file descriptor
exec 4< input.txt
read -u 4 line
exec 4<&- # Close file descriptor
Process Substitution
# Use command output as file
diff <(ls dir1) <(ls dir2)
while read line; do
echo "Line: $line"
done < <(find . -name "*.txt")
File Locking
# Exclusive lock
flock -x /tmp/lockfile command
flock -n /tmp/lockfile command # Non-blocking
# Shared lock
flock -s /tmp/lockfile command
# Lock file descriptor
exec 200>/tmp/lockfile
flock -n 200 || exit 1
Best Practices
Safety Practices
# Always quote file paths
cp "$source" "$destination"
# Check if file exists before operations
if [ -f "$file" ]; then
cp "$file" "$backup"
fi
# Use absolute paths for important operations
cp /full/path/to/source /full/path/to/dest
# Create backups before destructive operations
cp important_file{,.bak}
Performance Tips
# Use find instead of ls for large directories
find . -maxdepth 1 -name "*.txt"
# Avoid unnecessary file operations
# Bad: cat file | grep pattern
# Good: grep pattern file
# Use appropriate tools for file size
# Large files: use head/tail instead of loading entire file
head -n 100 large_file.txt