85% Fragmentation - CRON Defragment?

Just connected my 4TB Media HDD to my PC and it’s 85% fragmented after running nonstop for over a year. I was wondering if there’s a way to set a Crontab task to auto defragment every month, safely. I have docker running and would have to stop it and unmount, correct? Does anyone know how I could accomplish this?

Thank you.

did a quick Goog

Then add the sudo e4defrag /
to a crontab monthly entry

You can also check the fragmentation level with sudo e4defrag -c / to check if it’s bad
Remember this is only for HDD not SSD, that requires a TRIM

Cheers. I have an SSD and HDD connected, so I would just have to specify the HDD? Also, is it safe to do this without unmounting it first?

I just ran it on a few of my SBC’s on running/mounted OS’s…the files in use are skipped, most is not fragmented…but it went thru it, showed all that was completed and that which failed. Even worked on a SD card/USB and EMMC on a Rasbian build, a PROXMOX build (went thru and defragged the running virtual drives on the fly)

I don’t recommend this to be but once in literally a blue moon to defrag…but useful if you have alot of large static data…BTRFS and other write on read formats don’t have this issue…
Linux in general (ext4 and the like formats) rarely fragment on how it handles stuff…but it can get fragmented over time, but minimal fragmentation unlike that other OS that has defrag built in :wink: )

The / moniker defrags the entire “data set” I suppose…but you could tell it to defrag a particular mounted device or folder

sudo e4defrag /dev/sd (insert partition/drive of your mount here)
sudo e4defrag /mnt/(mounted folder here)

SSD you should be able to enable the trim.timer and it will periodically trim the drive in the background

sudo systemctl enable fstrim.timer

Thank you, this is running on a RPi4 and the SSD is connected over USB as the boot drive. Will the trim command still work? I have seen some conflicting results online.

Depends on what USB adapter you have, some works and some not. You can look at Jeff Geerling blog

1 Like

The fstrim command should usually work, and it runs automatically once a week via cron job on all attached drives.

1 Like