Understanding how filesystem type is determined before it is mounted

filesystemsmount

Is there any commandline tools to determine filesystem type on a block device before mounting it?and how is that achieved?

I believe it is possible since I usually mount external disks with

$ mount /dev/sdXX /mnt

mount automatically determines the filesystem for you. modern GUI tools even probe for disk usage and other info without mounting the filesystem if the driver for that fs is present.

the scenario here is that

  • the partition type and filesystem type may mismatch.
  • most linux filesystem use partition type "83", which doesn't offer much info about the fs it contains.
  • the corresponding drive may be absent, missing xfsprogs, hfsprogs, etc.

when auto-mounting fails, with an arbitrary partition or disk image in hand, it's simply not feasible to try each fs type candidate until you find the right one. or what if the filesystem is corrupt. you can't diagnose it with the designate tool as it's fs type is unknown.

i think superblock is where most filesystem stores its identifier. but different fs write superblock at different places.

is the raw dump of data of XXX bytes in the beginning sufficient to determine the fs type? is there a standard on where and in what format one should store such info?

any insight on this issue is much appreciated.

=-=

Update:

thanx for philag's answer.
so the usual file approach is actually the best approach.

my problem was just that i encountered a weird filesystem, whose file output is rather useless.

digging deeper into file's documentation (maybe the system calls it utilizes as well) should help me understand this issue better.

Best Answer

The first bytes (not literally, but usually in the first 4KiB) contain a signature, which especially crafted to be unique. The file utility can determine these signatures. See for yourself:

$ # Create an example file we can write to. vdisk stands for your partition.
$ dd if=/dev/zero of=vdisk bs=1M count=40
$ mkfs.ext2 -qF vdisk
$ file vdisk
vdisk: Linux rev 1.0 ext2 filesystem data, UUID=cce25572-...-f4eba2957279
$ mkfs.xfs -fq vdisk
$ file vdisk
vdisk: SGI XFS filesystem data (blksz 4096, inosz 256, v2 dirs)
$ # How does file find out? Let's look inside the partition
$ hexdump vdisk -C  | head -n 1
00000000  58 46 53 42 00 00 10 00  00 00 00 00 00 00 28 00  |XFSB..........(.|

To get a detailed list of filesystems that file recognizes, have a look at magic/Magdir/filesystems in the file source code. If you're just interested in those supported by your kernel, inspect include/linux/magic.h in your kernel sources.

If you are interested in a block device special the -s option is also useful, as is -L that will follow (dereference) symbolic links rather than operate on the link itself. For example if using a logical volume and device-mapper something like:

file -Ls /dev/mapper/home

may be useful.

Related Question