MBR tricks with Linux
The funny thing about the MBR is that it really isn't covered much in tutorials about installing Linux, however, it is a very crucial thing on your hard disk, and learning how to manipulate it is a very good skill indeed.
What is the MBR?
The MBR is an acronym that stands for Master Boot Record. It has two main functions: firstly, it holds the partition table of a disk, and secondly it can optionally contain executable code that the BIOS runs when the computer first starts up.
MBR structure
The MBR is located in the first 512 bytes of the disk (the first sector). It's organized as follows (taken from Wikipedia):
| Size (bytes) | Description |
| 446 | Executable code section |
| 4 | Optional Disk signature |
| 2 | Usually nulls |
| 64 | Partition table |
| 2 | MBR signature |
So what does this tell us? The most important thing to note is the overall size (512 bytes) and the executable code section (the first 446 bytes). Using this information you can do some fairly useful tasks.
Uses
Backing up a partition table
Probably one of the most useful things to do is to backup your partition table. This could be useful if you're planning to edit your partition table but don't want to lose the entire thing. To back it up, we're going to use the dd utility. To back up the MBR, enter the following at a Linux prompt:
dd if=/dev/hda of=/mbrbackup.bin bs=512 count=1
How does this work? if= refers to the input file. In this case it's your hard drive device, /dev/hda. (If you hard drive isn't /dev/hda for some reason, substitute it with the correct device.) of= refers to -- you guessed it -- the output file. In this case dd will create a new file in the root directory of the filesystem and save the contents of the MBR to this. bs refers to the block size (sector). Since the MBR is 512 bytes, you want to set it to that. Finally, count refers to the number of sectors to copy. There's only one MBR, so the count is set to 1. Now you should copy this file to an external device, because if the partition table gets damaged or erased, you won't be able to access the partition where you saved the file!
Restoring the MBR is equally easy:
dd if=/mbrbackup.bin of=/dev/hda bs=512 count=1
(This guide assumes you've already copied the mbrbackup.bin file from your backup media onto the current root partition.)
Erasing the partition table
If your partition table is for some reason toast and you just want to wipe it and start over, losing all your data, just write zeroes over the first 512 bytes of the disk:
dd if=/dev/zero of=/dev/hda bs=512 count=1
(However, if you wanted to write zeroes over the entire drive, you would just use dd if=/dev/zero of=/dev/hda.)
Conclusion
This guide is nothing new; these commands have existed for quite some time. However, it seems like many Linux tutorials neglect this topic, which is sad because it is very useful to be able to manipulate the first 512 bytes on your hard disk and understand how it all works.
