User Tools

Site Tools


cs:losetup

Table of Contents

losetup

In Linux everything is a file, so it is possible to use files as virtual disks with ease. losetup comes in when you want to use one virtual disk and partition it. losetup will read the partition table inside the file and prepare device files to use them.

Tutorial

dd is the simplest way to create an empty file, here is an example for 1 gigabyte image:

$ dd if=/dev/zero of=1gb_virtualdisk bs=1M count=1024

fdisk allows to make partitions inside the virtual disk:

$ fdisk 1gb_virtualdisk

Now we have a problem, how we can format the patitions fdisk made inside 1gb_virtualdisk? losetup can help, but it must be executed as superuser:

$ sudo losetup --find --nooverlap --partscan --show 1gb_image

This command will find (--find) a free loop device ensuring that no backing files are shared between loop devices (–nooverlap) and it will connect it to the file (1gb_image). Once done, losetup asks the kernel to scan the partitions inside the loop device (--partscan) and finally output the name of the used loop device on the shell (--show).

The short form of the command is:

$ sudo losetup -fLP --show 1gb_image

A possible output is:

/dev/loop0

/dev/loop0 will be a block device connected to the virtual disk and /dev/loop0pX (where X are integers) connect to the partitions inside the file.

Once the work is done, all the files can be deattached using -D

sudo losetup -D

It is also possible to use -d /dev/loop0 to deattach a single loop device.

Use case

The main use case is to create disk images, for example for using Qemu or before burning them on a CD.

cs/losetup.txt · Last modified: 2018/11/26 22:45 by paolo_bolzoni