Linux losetup Command

Linux 命令大全Linux Command Reference

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

Loop devices can virtualize files as block devices, thereby simulating an entire file system, allowing users to treat them as devices such as hard drives, CD-ROMs, or floppy drives, and mount them as directories for use.

Syntax

losetup [-d][-e <加密方式>][-o <平移数目>][循环设备代号][文件]

Parameters:

  • -d Detach the device.
  • -e<encryption method> Enable encryption encoding.
  • -o<offset number> Set the number of data offset.

Examples

(1) Create an empty disk image file. Here, create 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 as 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 disk image file floppy.img through the /tmp directory, just like accessing a real block device.

(4) Unmount the loop device.

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

A complete test example

1. First, create an empty file of 1G size:

# 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 as ext4 format:

# mkfs.ext4 loopfile.img
。。。。

3. Use the file command to check the formatted file type:

# 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 above 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

So in fact, mount -o loop has internally mounted the file and /dev/loop0 by default.

However, the first method (mount -o loop) does not apply to all scenarios. For example, if we want to create a hard disk file, partition it, and then mount one of the sub-partitions, the -o loop method cannot be used. Therefore, it must be done as follows:

# losetup /dev/loop1 loopfile.img
# fdisk /dev/loop1

6. Unmount the mount point:

# umount /mnt/loopback

Linux 命令大全Linux Command Reference

Other Extensions