# Files and Directories

This comprehensive guide covers file and directory operations in Linux, including management, permissions, and advanced operations.

## 📂 Basic File Operations

### File Creation and Viewing

```bash
# Create files
touch file.txt                    # Create empty file
echo "content" > file.txt         # Create with content
cat > file.txt                    # Create and input content
nano file.txt                     # Create/edit with text editor

# View files
cat file.txt                      # Display file content
less file.txt                     # Page through file
head -n 10 file.txt              # Show first 10 lines
tail -n 10 file.txt              # Show last 10 lines
tail -f file.txt                 # Follow file updates
```

### File Manipulation

```bash
# Copy files
cp source.txt dest.txt           # Copy file
cp -r source_dir dest_dir        # Copy directory
cp -p source.txt dest.txt        # Preserve attributes
cp -i source.txt dest.txt        # Interactive mode

# Move/rename files
mv old.txt new.txt              # Rename file
mv file.txt /path/to/dir/       # Move file
mv -i source dest               # Interactive mode
mv -u source dest               # Update only if newer

# Delete files
rm file.txt                     # Remove file
rm -r directory                 # Remove directory
rm -f file.txt                 # Force remove
rm -i file.txt                 # Interactive mode
```

## 📁 Directory Operations

### Directory Management

```bash
# Create directories
mkdir directory                 # Create directory
mkdir -p path/to/directory     # Create parent directories
mkdir -m 755 directory         # Create with permissions

# Navigate directories
cd /path/to/directory          # Change directory
cd ..                          # Go up one level
cd ~                          # Go to home directory
cd -                          # Go to previous directory

# Remove directories
rmdir directory               # Remove empty directory
rm -r directory              # Remove directory and contents
rm -rf directory             # Force remove directory
```

### Directory Information

```bash
# List contents
ls                           # List files and directories
ls -l                        # Long format listing
ls -a                        # Show hidden files
ls -R                        # Recursive listing
ls -lh                       # Human-readable sizes

# Directory size
du -sh directory            # Directory size
du -h --max-depth=1         # Size of subdirectories
ncdu                        # Interactive disk usage
```

## 🔍 File Search and Location

### Find Command

```bash
# Search by name
find /path -name "pattern"   # Find files by name
find /path -iname "pattern"  # Case-insensitive
find /path -type f          # Find only files
find /path -type d          # Find only directories

# Search by attributes
find /path -mtime +7        # Modified more than 7 days ago
find /path -size +100M      # Larger than 100MB
find /path -user username   # Owned by user
find /path -perm 644        # With specific permissions
```

### Locate and Which

```bash
# Quick file location
locate filename            # Find files in database
updatedb                   # Update locate database
which command             # Find command location
whereis command           # Find command binary/manual
```

## 📊 File Attributes

### File Information

```bash
# View file details
stat file                 # Detailed file information
file filename            # Determine file type
ls -l filename           # Show file attributes
ls -i filename           # Show inode number

# Timestamps
touch -a file            # Update access time
touch -m file            # Update modification time
touch -t 202312312359.59 file # Set specific time
```

### File Compression

```bash
# Compress files
gzip file               # Compress with gzip
bzip2 file             # Compress with bzip2
xz file                # Compress with xz

# Decompress files
gunzip file.gz         # Decompress gzip
bunzip2 file.bz2       # Decompress bzip2
unxz file.xz           # Decompress xz

# Archive operations
tar -czf archive.tar.gz files/    # Create gzip archive
tar -xzf archive.tar.gz           # Extract gzip archive
```

## 🔒 File Permissions and Ownership

### Permission Management

```bash
# Change permissions
chmod 755 file          # Set numeric permissions
chmod u+x file          # Add execute for user
chmod g-w file          # Remove write for group
chmod o=r file          # Set read-only for others

# Change ownership
chown user:group file   # Change owner and group
chown -R user directory # Recursive ownership change
chgrp group file       # Change group ownership
```

### Special Permissions

```bash
# Set special permissions
chmod u+s file         # Set SUID
chmod g+s directory    # Set SGID
chmod +t directory     # Set sticky bit

# View special permissions
ls -l /usr/bin/passwd  # View SUID example
ls -ld /tmp           # View sticky bit example
```

## 🔗 Links and References

### Link Creation

```bash
# Create links
ln -s target link      # Create symbolic link
ln target link         # Create hard link

# Manage links
readlink link         # Show link target
unlink link          # Remove link
ls -l link           # Show link information
```

## 💡 Best Practices

1. **File Organization**
   * Use meaningful names
   * Maintain consistent structure
   * Regular backups
   * Document file hierarchy
2. **Security**
   * Proper permissions
   * Regular permission audits
   * Secure file deletion
   * Access control
3. **Performance**
   * Regular cleanup
   * Optimize large directories
   * Monitor disk usage
   * Use appropriate filesystem

## 🔧 Troubleshooting

### Common Issues

```bash
# Permission denied
ls -l file            # Check permissions
namei -l /path/to/file # Check path permissions
lsattr file           # Check special attributes

# Disk space issues
df -h                 # Check disk space
du -sh /*             # Find large directories
lsof +L1              # Find deleted but open files
```

### File Recovery

```bash
# Recover deleted files
extundelete /dev/sda1 --restore-file path/to/file

# File system check
fsck /dev/sda1        # Check filesystem
e2fsck -f /dev/sda1   # Force check ext filesystems
```

## 📝 Advanced Operations

### File Monitoring

```bash
# Monitor file changes
inotifywait -m directory    # Monitor directory
tail -f file               # Follow file changes
watch -n 1 'ls -l file'    # Watch file attributes

# Process file handles
lsof file                 # List processes using file
fuser file               # Show file users
```

### Batch Operations

```bash
# Batch rename
rename 's/\.txt$/\.md/' *.txt    # Rename all .txt to .md
for f in *.txt; do mv "$f" "${f%.txt}.md"; done

# Batch processing
find . -type f -exec chmod 644 {} \;    # Change all file permissions
find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} \;
```
