How to Enable TRIM For SSD in Ubuntu

If you are using a Solid State Drive (SSD), you should know that you shouldn’t run any defragmentation or free space consolidation software on it. So how do you clean up your SSD and free up the empty space? TRIM is the command we use to inform the OS to do the cleaning job. Windows 8 comes with the “Optimize Drive” feature that can run the TRIM command regularly. What about Ubuntu? How can you enable TRIM for SSD in Ubuntu?

Note: The following steps will not work if you have encrypted your partition.

1. First, we have to make sure that the SSD in your computer supports TRIM. In Ubuntu, open a terminal and type:

sudo hdparm -I /dev/sda

If Ubuntu is not installed in the first partition of the SSD, change “sda” to reflect the partition where Ubuntu is residing. Scroll down the list till you see the “Enabled Supported:” section. Scroll down further and if you see something like “Data Set Management TRIM supported (limit 4 blocks)“, then TRIM is supported for your SSD.

trim-is-supported

2. Next, we need to test if the TRIM function is working in Ubuntu. In the terminal, type:

sudo fstrim -v /

This will clean up the root partition of the SSD. If successful, you should see something like this:

trim-is-working

3. Lastly, we will set a cron job for the OS to send the TRIM command once everyday.

sudo nano /etc/cron.daily/trim

Paste the following code into the blank area:

#!/bin/sh
fstrim -v /

If your HOME directory in located on another partition, you can add additional line to the end of the above code:

fstrim -v /home >> $LOG

If you want to save the output to a log file, you can use the following code instead:

#!/bin/sh
LOG=/var/log/trim.log
echo "*** $(date -R) ***" >> $LOG
fstrim -v / >> $LOG
fstrim -v /home >> $LOG

Save (Ctrl + o) and exit (Ctrl + x).

Now, make the cron job executable:

sudo chmod a+x /etc/cron.daily/trim

That’s it.

Image credit: My SSD