Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux losetup Command

Linux losetup Command

Linux Command Reference Linux Command Reference

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

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

Syntax

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

Parameters:

Example

(1) Create an empty disk image file; here we create a 1.44M floppy

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

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

$ losetup /dev/loop1 floppy.img

(3) Mount the block device

$ mount /dev/loop0 /tmp

After the three steps above, we can access the disk image file floppy.img through the /tmp directory just like 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 in 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

  1. Format the file as ext4:
# mkfs.ext4 loopfile.img

。。。。

  1. Use the file command to check the file type after formatting:
# file loopfile.img

loopfile.img: Linux rev 1.0 ext4 filesystem data, UUID=a9dfb4a0-6653-4407-ae05-7044d92c1159 (extents) (large files) (huge files)

  1. Prepare to mount the file above:
# 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 mount command above is actually equivalent to the following two commands:

# losetup /dev/loop0 loopfile.img

# mount /dev/loop0 /mnt/loopback

So in fact, mount -o loop internally mounts 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 its sub-partitions, the -o loop method cannot be used. In that case, you must do the following:

# losetup /dev/loop1 loopfile.img

# fdisk /dev/loop1

  1. Unmount the mount point:
# umount /mnt/loopback

Linux Command Reference Linux Command Reference