Easy Tutorial
❮ Linux Comm Userconf Linux Comm Unset ❯

Linux losetup Command

Linux Command Manual

The Linux losetup command is used to set up loop devices.

A loop device can virtualize a file into a block device, simulating an entire file system, allowing users to treat it as a hard drive, optical drive, or floppy drive, and mount it as a directory.

Syntax

losetup [-d][-e &lt;encryption method>][-o <offset>][loop device number][file]

Parameters:

Examples

(1) Create an empty disk image file, here creating a 1.44M floppy disk

$ dd if=/dev/zero of=floppy.img bs=512 count=2880

(2) Use losetup to virtualize the disk image file into a block device

$ losetup /dev/loop1 floppy.img

(3) Mount the block device

$ mount /dev/loop0 /tmp

After the above three steps, we can access the floppy.img disk image file through the /tmp directory, just like accessing a real block device.

(4) Detach the loop device

$ umount /tmp
$ losetup -d /dev/loop1

A complete test example

  1. First, create a 1G empty file:

    # dd if=/dev/zero of=loopfile.img bs=1G count=1
    1+0 records in
    1+0 records out
    1073741824 bytes (1.1 GB) copied, 69.3471 s, 15.5 MB/s
    
  2. Format the file to ext4:

    # mkfs.ext4 loopfile.img
    ...
    
  3. Use the file command to check the type of the formatted file:

    # file loopfile.img
    loopfile.img: Linux rev 1.0 ext4 filesystem data, UUID=a9dfb4a0-6653-4407-ae05-7044d92c1159 (extents) (large files) (huge files)
    
  4. Prepare to mount the file:

    # mkdir /mnt/loopback
    # mount -o loop loopfile.img /mnt/loopback
    

The -o loop option of the mount command can mount any loopback file system.

The above mount command is actually equivalent to the following two commands:

# losetup /dev/loop0 loopfile.img
# mount /dev/loop0 /mnt/loopback

Therefore, internally, the mount -o loop command has already mounted the file and /dev/loop0 by default.

However, the first method (mount -o loop) cannot be applied to all scenarios. For example, if we want to create a disk file, then partition the file, and then mount one of the sub-partitions, we cannot use the -o loop method. Therefore, we must do the following:

# losetup /dev/loop1 loopfile.img
# fdisk /dev/loop1
  1. Unmount the mount point:
    # umount /mnt/loopback
    

Linux Command Manual

❮ Linux Comm Userconf Linux Comm Unset ❯