NerdVana

Enter any 11-digit prime number to continue...

fstrim cron job

Written by Eric Schwimmer

This little guy will trim all of the mounts on your system that support it, skipping rotational drives (which sometimes support trim, bizarrely) and NVMe drives (which usually support trim, but whose vendors often recommend against running it on). It will pick apart mdadm arrays to see if their base members are trimmable, and just skip the whole deal if run on a VM:

#!/bin/bash

# Quick function to check if a device is trimmable
trimmable() {
    dev=$1
    basedev=${dev%%[0-9]*}
    ( [[ $dev = *nvme* ]] \
            || egrep -sq '^1$' /sys/block/$/queue/rotational ) \
        && return 0
    egrep -vsq '^0$' /sys/block/$/queue/discard_max_bytes \
        && return 1
    return 0

}

# Exit early if we are in a VM
grep -q '^flags.* hypervisor ' /proc/cpuinfo && exit 0

# Iterate over all of our mounts
findmnt -sen -o SOURCE,TARGET | while read dev_path mount; do
    dev=${dev_path#/*/}

    # If this is a mdadm array, look at its members individually
    if [[ "$dev" = md[0-9]* ]]; then
        for dev_path in /sys/block/$dev/md/dev-*; do
            md_dev=${dev_path##*-}
            trimmable $dev || continue 2
        done

    # Otherwise check if the base device is trimmable
    else
        trimmable $dev || continue
    fi

    fstrim -v $mount
done