Skip to content

Instantly share code, notes, and snippets.

@vijinho
Last active January 6, 2025 11:14
Show Gist options
  • Save vijinho/d4c313d70fad09f16ce93870562cec2e to your computer and use it in GitHub Desktop.
Save vijinho/d4c313d70fad09f16ce93870562cec2e to your computer and use it in GitHub Desktop.
Clear standby mode and set the disk sleep-time in Linux
#!/bin/bash
# Function to check if a device file exists and is an HDD
is_valid_device() {
if ! test -b "$DEVICE"; then
echo "Error: '$DEVICE' is not a valid block device."
return 1
fi
if ! grep -q "$DEVICE" /proc/partitions; then
echo "Error: '$DEVICE' does not exist or is not listed in /proc/partitions."
return 1
fi
# Check if the device is an HDD
if ! lsblk -no TYPE "$DEVICE" | grep -q "disk"; then
echo "Error: '$DEVICE' is not a disk (e.g., it might be a partition or USB device)."
return 1
fi
return 0
}
# Default sleep time in seconds
SLEEP_TIME=230
# Parse command-line options using getopt
OPTS=$(getopt -o t: --long sleep-time: -n 'set_sleep_time.sh' -- "$@")
if [ $? != 0 ] ; then echo "Failed to parse options." >&2 ; exit 1 ; fi
eval set -- "$OPTS"
while true; do
case "$1" in
-t | --sleep-time )
SLEEP_TIME="$2"
shift 2;;
-- )
shift
break ;;
* )
echo "Invalid option: $1"
exit 1 ;;
esac
done
# Check if the correct number of arguments is provided after parsing options
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <device_file> [-t|--sleep-time <seconds>]"
exit 1
fi
DEVICE=$1
# Validate the device before proceeding
if ! is_valid_device; then
exit 1
fi
# Clear the STANDBY mode and set the sleep time to the specified value or default (230 seconds)
sudo sdparm --clear=STANDBY "$DEVICE"
if [ $? -ne 0 ]; then
echo "Error: Failed to clear standby mode for device '$DEVICE'."
exit 1
fi
sudo hdparm -S $SLEEP_TIME "$DEVICE"
if [ $? -ne 0 ]; then
echo "Error: Failed to set sleep time for device '$DEVICE'."
exit 1
fi
echo "Successfully cleared standby mode and set the sleep time to $SLEEP_TIME seconds for device '$DEVICE'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment