Adding a USB hard drive to Raspberry Pi

I’m assuming the drive you are going to use contains no data you want, that it is the first external drive you are adding and that it is going to be permanent (not portable between pc/mac/pi), also that you have a powered USB hub plugged into your Pi (the Pi does not have enough power to run most hard drives).

Plug the drive in and wait for a few seconds for it to be recognised.

sudo fdisk -l

This will list all the drives seen by the Raspberry Pi. your USB drive should be at the bottom, probably called ‘/dev/sda1' or something similar. If you have multiple partitions on the drive you may have ‘sda1', 'sda2', 'sda3' too.

Now enter

sudo fdisk /dev/sda

it will reply ‘Command (m for help):' type P to list the partitions

Delete all of the partitions by typing ‘d‘ and entering the number of each partition in turn. type ‘p‘ after each to check your progress.

When you have no partitions left, create a new one. Press ‘n‘ and to each of the questions press ‘p‘ for primary, return for the first block and return again for the last block. This will give you the entire disk as a single primary partition.

Now use the ‘p‘ command again to see your new partition, then write the changes you have made to the disk by pressing ‘w‘ to commit.

Run the 'sudo fdisk -l' command to see your new disk.

Now you can make your file system. Use the mkfs command.

sudo mkfs -t ext4 /dev/sda1

This will create your superblocks and set up the partition as ext4. Now you need to create a mount point. I’ll be mounting this drive at /mnt/pidata

sudo mkdir /pidata
sudo chown pi:pi /mnt/pidata
sudo mount /dev/sda1 /mnt/pidata
df

The drive should appear in the drive list. Now we need to get the UUID of the drive, this is so that when we hotplug the drive (or another) the Pi doesn’t get confused about what drive is in what socket.

ls -laF /dev/disk/by-uuid/

Make a note of the long hex string that is the unique ID of the drive, in my case it was 'a34c1ad6-e305-4c5e-a09a-114712c3e798', you’ll be needing it in a sec.

Now you need to add the drive to fstab so that it mounts at startup

sudo nano /etc/fstab

Add a line to the bottom of the file

UUID=a34c1ad6-e305-4c5e-a09a-114712c3e798 /mnt/pidata ext4 defaults 0 0

Where the uuid is YOUR uuid and the mount point is YOUR mount point. Write out the file and exit nano.

Reboot.

The drive should be mounted when the Raspberry Pi comes back up, you should be able to touch /mnt/pidata/test.tst to create a file on the drive without any permissions issues.

Leave a Reply

Your email address will not be published. Required fields are marked *