Skip to content

Instantly share code, notes, and snippets.

@carlhannes
Created December 25, 2023 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlhannes/b1eb8e183ca3cdd20e2833e38a680d39 to your computer and use it in GitHub Desktop.
Save carlhannes/b1eb8e183ca3cdd20e2833e38a680d39 to your computer and use it in GitHub Desktop.
hdd-spindown.sh
#!/bin/bash
# 1. Check and install hdparm if not installed
if ! which hdparm > /dev/null; then
echo "hdparm not found! Installing..."
apt-get update
apt-get install -y hdparm
fi
# 2. List HDDs
echo "Listing available HDDs:"
mapfile -t drives < <(lsblk -d -o name,rota | grep ' 1$' | awk '{print $1}')
for drive in "${drives[@]}"; do
type=$(udevadm info --query=all --name="/dev/$drive" | grep "ID_BUS" | cut -d"=" -f2)
echo "- /dev/$drive ($type)"
done
# 3. Ask user for the drive
echo "Enter the drive path (e.g., /dev/sda) for spindown operation:"
read selected_drive
# Check if selected drive is valid
if ! [[ " ${drives[@]} " =~ " ${selected_drive#/dev/} " ]]; then
echo "Invalid selection!"
exit 1
fi
# 4. Run hdparm
hdparm -S 242 $selected_drive
# 5. Create a boot-time shell script
script_path="/usr/local/bin/spindown_${selected_drive#/dev/}.sh"
cat > $script_path <<EOL
#!/bin/bash
hdparm -S 242 $selected_drive
EOL
chmod +x $script_path
# 6. Create a systemd service
service_path="/etc/systemd/system/spindown_${selected_drive#/dev/}.service"
cat > $service_path <<EOL
[Unit]
Description=Spindown for $selected_drive
[Service]
Type=oneshot
ExecStart=$script_path
[Install]
WantedBy=multi-user.target
EOL
# 7. Enable and start the systemd service
systemctl daemon-reload
systemctl enable spindown_${selected_drive#/dev/}.service
systemctl start spindown_${selected_drive#/dev/}.service
# 8. List the systemd service
systemctl status spindown_${selected_drive#/dev/}.service
echo "Setup complete for $selected_drive!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment