How to create and delete loopback devices by losetup command?
Environment
- Red Hat Enterprise Linux 7
- Red Hat Enterprise Linux 8
- Red Hat Enterprise Linux 9
Issue
- How can I create and delete loopback devices by losetup command?
- Use
losetupto create a loop device for an existing FS/image.
Resolution
-
Creating a loopback device:
-
Preparing an appropriately sized file for the loopback device:
For example:
# dd if=/dev/zero of=/tmp/test.img bs=1M count=100 -
Attaching a device to the file:
Specifying a loop device directly or using the
-foption to automatically assign an unused device# losetup /dev/loop0 /tmp/test.imgor
# losetup -f /tmp/test.img -
Checking the created loop device, and creating/mounting an FS:
You can check the status of all loop devices with the
-aoption:# losetup -a /dev/loop0: [64770]:134591359 (/tmp/test.img)To check a specific device by reverse lookup from a file, use the
-joption:# losetup -j /tmp/test.img /dev/loop0: [64770]:134591359 (/tmp/test.img)Format and mount with a specific file system:
# mkfs.xfs /tmp/test.img # mount /dev/loop0 /mnt -v
-
-
Deleting a loopback device:
If the loop device is mounted, unmount it, delete the loop device, and then delete the corresponding file:
# umount /dev/loop0 # losetup -d /dev/loop0 # rm -f /tmp/test.img -
For any existing FS image, or FS metadata where signature is detected, the FS could be mounted using
losetupdirectly as a loop device:# losetup -f </path/to/image/having/valid/signature>Note: The image layout must be inspected first for identifying what type of image it is.
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.