#!/bin/bash set -e #set -x DEFRAG_ROOT="$1" SHARE_ROOT="/mnt2" LOG=~jason/logs/btrfs-defrag-$(date '+%Y-%m-%d_%H-%M').log function log() { date_str=`date '+%Y-%m-%d %H:%M:%S'` echo "[$date_str]: $1" 2>&1 | tee -a $LOG } CURR_USER=`whoami` if [ "$CURR_USER" != "root" ]; then echo "Must be run as root" exit -1 fi function logCmd() { cmd="$@" log "Running '${cmd}'" time $cmd 2>&1 | tee -a $LOG } function doDefrag() { log "Starting defrag of: $DEFRAG_ROOT" logCmd /usr/sbin/btrfs filesystem defrag -rvf "$DEFRAG_ROOT" } function defragAll() { for d in $SHARE_ROOT/*; do DEFRAG_ROOT=$d time doDefrag done } if [ "$DEFRAG_ROOT" = "" ]; then echo "No share specified. Going to defrag all shares under $SHARE_ROOT" #read -p "Press any key to continue, or ctrl+C to cancel." time defragAll else time doDefrag fi log "Done"