Skip to content

Instantly share code, notes, and snippets.

@llagerlof
Created June 14, 2023 12:15
Show Gist options
  • Save llagerlof/b0be9da2aa95bf158770558ffe3e0d53 to your computer and use it in GitHub Desktop.
Save llagerlof/b0be9da2aa95bf158770558ffe3e0d53 to your computer and use it in GitHub Desktop.
Shell script (bash) that shows the available space of the largest partition of each disk. Ignores disks without partitions.
#!/bin/bash
# Example output:
# Disk: sda (894.25 GB)
# Largest partition: sda1
# Used space: 878 GB
# Available space: 17 GB
# Disk: sdb (222.57 GB)
# Largest partition: sdb2
# Used space: 189 GB
# Available space: 34 GB
# Get a list of all disks
DISKS=$(lsblk -dno NAME,TYPE | awk '$2=="disk"{print $1}')
# For each disk
for DISK in $DISKS; do
# Get a list of all partitions on the disk
PARTITIONS=$(lsblk /dev/"$DISK" -o NAME,TYPE | awk '$2=="part"{print $1}' | sed 's/[^a-zA-Z0-9]//g')
# Initialize the maximum size and corresponding partition to be empty
MAX_SIZE=0
MAX_PARTITION=""
# For each partition
for PARTITION in $PARTITIONS; do
# Get the size of the partition in GB
SIZE=$(lsblk /dev/"$PARTITION" -o SIZE -b --output=SIZE | tail -n1 | awk '{ printf "%.2f", $1/1024/1024/1024 }')
# If this is the largest partition we've seen so far
if (( $(echo "$SIZE > $MAX_SIZE" | bc -l) )); then
# Update the maximum size and partition
MAX_SIZE=$SIZE
MAX_PARTITION=$PARTITION
fi
done
# If a partition was found on the disk
if [ "$MAX_PARTITION" != "" ]; then
# Get the used and available space on the partition in GB
USED_SPACE=$(df -BG --output=used /dev/"$MAX_PARTITION" | tail -n1 | sed 's/G//')
AVAIL_SPACE=$(df -BG --output=avail /dev/"$MAX_PARTITION" | tail -n1 | sed 's/G//')
FULL_CAPACITY="$(lsblk /dev/"$DISK" -o SIZE -b --output=SIZE | tail -n1 | awk '{ printf "%.2f GB", $1/1024/1024/1024 }')"
# Print the disk and partition information
echo -e "Disk: $DISK (\033[1m$FULL_CAPACITY\033[0m)"
echo " Largest partition: $MAX_PARTITION"
echo " Used space: $USED_SPACE GB"
echo -e " \033[1mAvailable space: $AVAIL_SPACE GB\033[0m"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment