Skip to main content

Mount va Unmount Operations

Mount va unmount operations - bu Linux tizimida storage device'lar va filesystem'larni tizimga ulash va ajratish jarayoni. Bu file system hierarchy'da device'larni integrate qilish uchun zarur.

Mount Concepts (Asosiy Tushunchalar)

Mount Point

# Mount Point - filesystem'ni ulash uchun directory
# Hierarchy - barcha filesystem'lar bitta tree'da
# Root filesystem (/) - asosiy filesystem
# Mount target - mount qilinadigan directory

# Example mount points:
/ # Root filesystem
/home # User home directories
/var # Variable data
/tmp # Temporary files
/boot # Boot files
/mnt # Temporary mount point
/media # Removable media

Filesystem Types

# Local filesystems
ext2, ext3, ext4 # Linux native filesystems
xfs # High-performance filesystem
btrfs # Advanced filesystem with snapshots
ntfs # Windows filesystem
vfat, fat32 # DOS/Windows compatibility
iso9660 # CD/DVD filesystem

# Network filesystems
nfs # Network File System
cifs, smb # Windows shares
sshfs # SSH filesystem
ftp # FTP filesystem

# Virtual filesystems
proc # Process information
sysfs # System information
tmpfs # RAM filesystem
devtmpfs # Device filesystem

Basic Mount Operations

Mount Command Syntax

# Basic syntax
mount [options] device mountpoint
mount [options] -t filesystem device mountpoint

# Examples
sudo mount /dev/sdb1 /mnt # Mount device to /mnt
sudo mount -t ext4 /dev/sdb1 /data # Specify filesystem type
sudo mount -o ro /dev/sdb1 /mnt # Mount read-only

Mount Examples

# Mount USB drive
sudo mount /dev/sdb1 /media/usb

# Mount with specific filesystem
sudo mount -t ntfs /dev/sdb1 /mnt/windows

# Mount ISO file
sudo mount -o loop disk.iso /mnt/iso

# Mount with options
sudo mount -o rw,uid=1000,gid=1000 /dev/sdb1 /mnt/drive

# Mount network share
sudo mount -t nfs server:/path /mnt/nfs
sudo mount -t cifs //server/share /mnt/share -o username=user,password=pass

Current Mounts Information

# Show mounted filesystems
mount # All mounted filesystems
mount | grep "^/dev" # Only device mounts
mount | column -t # Formatted output

# Alternative commands
cat /proc/mounts # Kernel view of mounts
findmnt # Tree view of mounts
findmnt / # Specific mount point
findmnt -D # Show device info
findmnt -t ext4 # Show specific filesystem type

# Mount statistics
findmnt -o TARGET,SOURCE,FSTYPE,SIZE,USED,AVAIL,USE%

Mount Options

Common Mount Options

# Read/Write options
rw # Read-write (default)
ro # Read-only

# User and permission options
uid=1000 # Set file owner
gid=1000 # Set file group
umask=022 # Set file permissions mask
user # Allow regular users to mount
users # Allow any user to unmount
nouser # Only root can mount (default)

# Security options
exec # Allow execution of binaries (default)
noexec # Disable execution
suid # Allow setuid (default)
nosuid # Disable setuid
dev # Allow device files (default)
nodev # Disable device files

# Performance options
sync # Synchronous I/O
async # Asynchronous I/O (default)
atime # Update access time (default)
noatime # Don't update access time
relatime # Update access time relatively

Filesystem-Specific Options

# ext2/3/4 options
sudo mount -o errors=remount-ro /dev/sdb1 /mnt # Remount ro on errors
sudo mount -o errors=continue /dev/sdb1 /mnt # Continue on errors
sudo mount -o nobarrier /dev/sdb1 /mnt # Disable barriers

# NTFS options
sudo mount -t ntfs -o uid=1000,gid=1000,umask=022 /dev/sdb1 /mnt
sudo mount -t ntfs -o windows_names /dev/sdb1 /mnt # Windows naming

# VFAT options
sudo mount -t vfat -o iocharset=utf8 /dev/sdb1 /mnt
sudo mount -t vfat -o codepage=437 /dev/sdb1 /mnt

# NFS options
sudo mount -t nfs -o vers=4,rsize=8192,wsize=8192 server:/path /mnt
sudo mount -t nfs -o soft,timeo=30,retrans=3 server:/path /mnt

Advanced Mount Options

# Bind mounts
sudo mount --bind /old/path /new/path # Bind mount directory
sudo mount --rbind /old/path /new/path # Recursive bind mount

# Loop mounts
sudo mount -o loop disk.img /mnt # Mount disk image
sudo mount -o loop,offset=1048576 disk.img /mnt # Mount with offset

# Remount with different options
sudo mount -o remount,ro /dev/sdb1 # Remount as read-only
sudo mount -o remount,rw /dev/sdb1 # Remount as read-write
sudo mount -o remount,noatime /home # Add noatime option

Unmount Operations

Basic Unmount

# Unmount by mount point
sudo umount /mnt
sudo umount /media/usb

# Unmount by device
sudo umount /dev/sdb1

# Unmount all instances
sudo umount -a -t ext4 # Unmount all ext4 filesystems
sudo umount -a -O no_netdev # Unmount all local filesystems

Force Unmount

# Lazy unmount (unmount when not busy)
sudo umount -l /mnt # Lazy unmount

# Force unmount (dangerous!)
sudo umount -f /mnt # Force unmount

# Check what's using the mount
sudo lsof /mnt # List open files
sudo fuser -v /mnt # Show processes using mount point
sudo fuser -k /mnt # Kill processes using mount point

# Combined approach
sudo fuser -km /mnt && sudo umount /mnt

Unmount Troubleshooting

# Device busy error troubleshooting
# 1. Check open files
sudo lsof /mnt
sudo fuser -v /mnt

# 2. Check current directory
pwd # Are you in the mount point?
cd / # Change to root

# 3. Check background processes
sudo ps aux | grep /mnt

# 4. Stop services that might be using it
sudo systemctl stop service_name

# 5. Use lazy unmount as last resort
sudo umount -l /mnt

/etc/fstab Configuration

fstab Format

# /etc/fstab format:
# device mountpoint filesystem options dump pass

# Examples:
UUID=12345678-1234-1234-1234-123456789012 / ext4 defaults 0 1
UUID=87654321-4321-4321-4321-210987654321 /home ext4 defaults 0 2
/dev/sda3 none swap sw 0 0
tmpfs /tmp tmpfs size=2G,nodev,nosuid 0 0

# Fields explanation:
# 1. Device: UUID, LABEL, or device path
# 2. Mount point: where to mount
# 3. Filesystem type: ext4, xfs, swap, etc.
# 4. Mount options: defaults, ro, noatime, etc.
# 5. Dump: backup utility flag (0=no, 1=yes)
# 6. Pass: fsck order (0=no check, 1=root, 2=other)

fstab Examples

# Root filesystem
UUID=a1b2c3d4-e5f6-7890-abcd-ef1234567890 / ext4 defaults,errors=remount-ro 0 1

# Home partition
UUID=b2c3d4e5-f6g7-8901-bcde-f12345678901 /home ext4 defaults,nodev 0 2

# Swap partition
UUID=c3d4e5f6-g7h8-9012-cdef-123456789012 none swap sw 0 0

# Temporary filesystem in RAM
tmpfs /tmp tmpfs defaults,size=1G,nodev,nosuid,noexec 0 0

# External drive with auto-mount
UUID=d4e5f6g7-h8i9-0123-def1-234567890123 /media/backup ext4 defaults,noauto,user 0 0

# Network filesystem
server.local:/shared /mnt/shared nfs defaults,_netdev 0 0

# Windows share
//server/share /mnt/windows cifs credentials=/etc/samba/credentials,uid=1000,gid=1000 0 0

fstab Management

# Test fstab without rebooting
sudo mount -a # Mount all fstab entries
sudo mount -a -f # Fake mount (test syntax)

# Check specific entry
sudo mount /home # Mount /home from fstab

# Validate fstab syntax
findmnt --verify # Verify fstab syntax
findmnt --verify --verbose # Detailed verification

# Backup fstab
sudo cp /etc/fstab /etc/fstab.backup
sudo cp /etc/fstab /etc/fstab.$(date +%Y%m%d)

# Edit safely
sudo vim /etc/fstab
# Always test with: sudo mount -a

Auto-mounting

systemd Auto-mount

# Create mount unit
sudo vim /etc/systemd/system/data.mount

[Unit]
Description=Data Drive
What=/dev/disk/by-uuid/12345678-1234-1234-1234-123456789012
Where=/data
Type=ext4
Options=defaults

[Install]
WantedBy=multi-user.target

# Create automount unit
sudo vim /etc/systemd/system/data.automount

[Unit]
Description=Data Drive Automount
Where=/data

[Automount]
TimeoutIdleSec=60

[Install]
WantedBy=multi-user.target

# Enable automount
sudo systemctl daemon-reload
sudo systemctl enable data.automount
sudo systemctl start data.automount

autofs Configuration

# Install autofs
sudo apt install autofs # Ubuntu/Debian
sudo yum install autofs # CentOS/RHEL

# Configure autofs
sudo vim /etc/auto.master
# Add line: /mnt/auto /etc/auto.misc --timeout=60

sudo vim /etc/auto.misc
# Add entries:
# usb -fstype=auto,uid=1000,gid=1000 :/dev/sdb1
# cdrom -fstype=iso9660,ro :/dev/cdrom

# Start autofs service
sudo systemctl enable autofs
sudo systemctl start autofs

# Test automount
ls /mnt/auto/usb # Automatically mounts USB

Network Mounts

NFS Mount

# Install NFS client
sudo apt install nfs-common # Ubuntu/Debian
sudo yum install nfs-utils # CentOS/RHEL

# Show available NFS exports
showmount -e nfs-server
showmount -a nfs-server # Show active mounts

# Mount NFS share
sudo mount -t nfs nfs-server:/path /mnt/nfs
sudo mount -t nfs -o vers=4,rsize=8192,wsize=8192 nfs-server:/path /mnt/nfs

# NFS in fstab
nfs-server:/shared /mnt/shared nfs defaults,_netdev,timeo=30 0 0

# NFS options
# vers=3,4 NFS version
# rsize=8192 Read buffer size
# wsize=8192 Write buffer size
# hard Hard mount (default)
# soft Soft mount
# timeo=30 Timeout value
# retrans=3 Number of retries

CIFS/SMB Mount

# Install CIFS utilities
sudo apt install cifs-utils # Ubuntu/Debian
sudo yum install cifs-utils # CentOS/RHEL

# Mount Windows share
sudo mount -t cifs //server/share /mnt/share -o username=user,password=pass
sudo mount -t cifs //server/share /mnt/share -o credentials=/etc/samba/credentials

# Credentials file
sudo vim /etc/samba/credentials
username=myuser
password=mypass
domain=mydomain

sudo chmod 600 /etc/samba/credentials

# CIFS in fstab
//server/share /mnt/share cifs credentials=/etc/samba/credentials,uid=1000,gid=1000,iocharset=utf8 0 0

# CIFS options
# uid=1000 File owner
# gid=1000 File group
# file_mode=0644 File permissions
# dir_mode=0755 Directory permissions
# iocharset=utf8 Character encoding
# cache=strict Caching mode

SSHFS Mount

# Install SSHFS
sudo apt install sshfs # Ubuntu/Debian
sudo yum install fuse-sshfs # CentOS/RHEL

# Mount remote directory via SSH
sshfs user@server:/remote/path /local/mount
sshfs user@server:/remote/path /local/mount -o allow_other

# SSHFS options
sshfs user@server:/path /mnt -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3

# Unmount SSHFS
fusermount -u /local/mount

# SSHFS in fstab
user@server:/path /mnt/remote fuse.sshfs defaults,_netdev,users,allow_other,reconnect 0 0

Special Mounts

tmpfs (RAM filesystem)

# Mount tmpfs
sudo mount -t tmpfs tmpfs /mnt/ramdisk
sudo mount -t tmpfs -o size=1G tmpfs /mnt/ramdisk
sudo mount -t tmpfs -o size=512M,nodev,nosuid,noexec tmpfs /tmp

# tmpfs in fstab
tmpfs /tmp tmpfs size=1G,nodev,nosuid,noexec 0 0
tmpfs /var/tmp tmpfs size=512M,nodev,nosuid 0 0

# Check tmpfs usage
df -h /tmp
mount | grep tmpfs

Bind Mounts

# Bind mount directory
sudo mount --bind /original/path /new/path
sudo mount --rbind /original/path /new/path # Recursive bind

# Bind mount in fstab
/original/path /new/path none bind 0 0
/original/path /new/path none rbind 0 0

# Use cases for bind mounts:
# - Chroot environments
# - Container isolation
# - Making directories available in multiple locations
# - Legacy application compatibility

Loop Mounts

# Create disk image
dd if=/dev/zero of=disk.img bs=1M count=100
mkfs.ext4 disk.img

# Mount disk image
sudo mount -o loop disk.img /mnt/image

# Mount with offset (for partition images)
sudo mount -o loop,offset=1048576 disk.img /mnt/partition

# Mount ISO files
sudo mount -o loop linux.iso /mnt/iso

# Encrypted loop mount
sudo cryptsetup luksFormat disk.img
sudo cryptsetup luksOpen disk.img encrypted_disk
sudo mount /dev/mapper/encrypted_disk /mnt/encrypted

Mount Monitoring and Automation

Mount Monitoring Script

#!/bin/bash
# mount-monitor.sh - Monitor mount points and auto-remount if needed

MOUNT_POINTS=(
"/home"
"/var"
"/data"
"/backup"
)

LOG_FILE="/var/log/mount-monitor.log"

log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

check_mount() {
local mount_point=$1

if mountpoint -q "$mount_point"; then
log_message "OK: $mount_point is mounted"
return 0
else
log_message "ERROR: $mount_point is not mounted"
return 1
fi
}

remount_from_fstab() {
local mount_point=$1

log_message "Attempting to remount $mount_point from fstab"

if mount "$mount_point"; then
log_message "SUCCESS: Remounted $mount_point"
return 0
else
log_message "FAILED: Could not remount $mount_point"
return 1
fi
}

send_alert() {
local mount_point=$1
local status=$2

if command -v mail >/dev/null 2>&1; then
echo "Mount Alert: $mount_point is $status on $(hostname) at $(date)" | \
mail -s "Mount Alert: $mount_point $status" admin@company.com
fi

# Log to syslog
logger -t mount-monitor "Mount Alert: $mount_point is $status"
}

# Main monitoring loop
for mount_point in "${MOUNT_POINTS[@]}"; do
if ! check_mount "$mount_point"; then
if remount_from_fstab "$mount_point"; then
send_alert "$mount_point" "remounted automatically"
else
send_alert "$mount_point" "failed to remount"
fi
fi
done

# Crontab entry:
# */5 * * * * /usr/local/bin/mount-monitor.sh

Automatic USB Mount Script

#!/bin/bash
# usb-automount.sh - Automatically mount USB devices

USB_MOUNT_BASE="/media/usb"
LOG_FILE="/var/log/usb-automount.log"

log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

mount_usb() {
local device=$1
local label=$(blkid -o value -s LABEL "$device" 2>/dev/null)
local uuid=$(blkid -o value -s UUID "$device" 2>/dev/null)
local fstype=$(blkid -o value -s TYPE "$device" 2>/dev/null)

# Determine mount point
if [ -n "$label" ]; then
mount_point="$USB_MOUNT_BASE/$label"
elif [ -n "$uuid" ]; then
mount_point="$USB_MOUNT_BASE/$uuid"
else
mount_point="$USB_MOUNT_BASE/$(basename $device)"
fi

# Create mount point
mkdir -p "$mount_point"

# Mount options based on filesystem
case "$fstype" in
"vfat"|"fat32"|"ntfs")
mount_opts="uid=1000,gid=1000,umask=022"
;;
"ext2"|"ext3"|"ext4")
mount_opts="defaults"
;;
*)
mount_opts="defaults"
;;
esac

# Attempt to mount
if mount -t "$fstype" -o "$mount_opts" "$device" "$mount_point"; then
log_message "Mounted $device ($fstype) at $mount_point"

# Set permissions for common directories
chmod 755 "$mount_point"

return 0
else
log_message "Failed to mount $device"
rmdir "$mount_point" 2>/dev/null
return 1
fi
}

unmount_usb() {
local device=$1
local mount_point=$(findmnt -n -o TARGET "$device" 2>/dev/null)

if [ -n "$mount_point" ]; then
if umount "$device"; then
log_message "Unmounted $device from $mount_point"
rmdir "$mount_point" 2>/dev/null
else
log_message "Failed to unmount $device"
fi
fi
}

# Detect USB devices
for device in /dev/sd[b-z][0-9]; do
if [ -b "$device" ]; then
# Check if already mounted
if ! mountpoint -q "$(findmnt -n -o TARGET "$device" 2>/dev/null)"; then
# Check if it's a USB device
device_path=$(udevadm info --query=path --name="$device")
if echo "$device_path" | grep -q "usb"; then
mount_usb "$device"
fi
fi
fi
done

# Usage with udev rules:
# Create /etc/udev/rules.d/99-usb-automount.rules:
# ACTION=="add", KERNEL=="sd[b-z][0-9]", RUN+="/usr/local/bin/usb-automount.sh"

Mount Statistics and Analysis

#!/bin/bash
# mount-stats.sh - Analyze mount statistics and usage

generate_mount_report() {
echo "=== Mount Point Analysis Report ==="
echo "Generated: $(date)"
echo

echo "=== Current Mount Points ==="
findmnt -D -o TARGET,SOURCE,FSTYPE,SIZE,USED,AVAIL,USE%
echo

echo "=== Mount Options Analysis ==="
mount | while read line; do
device=$(echo "$line" | awk '{print $1}')
mount_point=$(echo "$line" | awk '{print $3}')
options=$(echo "$line" | grep -o '(.*)')

if [[ "$device" =~ ^/dev/ ]]; then
echo "$mount_point: $options"
fi
done
echo

echo "=== Filesystem Type Distribution ==="
findmnt -n -o FSTYPE | grep -v "^$" | sort | uniq -c | sort -nr
echo

echo "=== Space Usage Alerts ==="
df -h | awk 'NR>1 && $5+0 > 80 {print "WARNING: " $0 " is " $5 " full"}'
echo

echo "=== Mount Performance Analysis ==="
for mount_point in $(findmnt -n -o TARGET | grep "^/"); do
if [ -d "$mount_point" ]; then
echo -n "$mount_point: "
# Simple read test
time_result=$(timeout 5 time sh -c "dd if=$mount_point/test_file of=/dev/null bs=1M count=1 2>/dev/null" 2>&1 | grep real)
if [ $? -eq 0 ]; then
echo "$time_result"
else
echo "Cannot test (no test file or permission denied)"
fi
fi
done
echo

echo "=== fstab vs Current Mounts ==="
echo "Mounts defined in fstab but not currently mounted:"
awk '$2 !~ /^#/ && $2 != "none" && $2 != "swap" {print $2}' /etc/fstab | while read fstab_mount; do
if ! mountpoint -q "$fstab_mount" 2>/dev/null; then
echo " $fstab_mount"
fi
done
echo

echo "=== Network Mount Status ==="
findmnt -t nfs,cifs,sshfs -o TARGET,SOURCE,FSTYPE
}

# Generate report
generate_mount_report

# Save to file
generate_mount_report > "/var/log/mount-report-$(date +%Y%m%d).txt"

Bu tutorial mount va unmount operations bo'yicha comprehensive guide beradi - basic mount operations'dan tortib advanced network mounts, auto-mounting va monitoring techniques bilan birga.