Skip to content

Instantly share code, notes, and snippets.

@austonpramodh
Created March 15, 2024 22:51
Show Gist options
  • Select an option

  • Save austonpramodh/f45701c800507163c4498420d186b487 to your computer and use it in GitHub Desktop.

Select an option

Save austonpramodh/f45701c800507163c4498420d186b487 to your computer and use it in GitHub Desktop.
Stop Linux from sleeing for certain time!
#!/bin/bash
# Function to handle Ctrl+C
function ctrl_c() {
echo -e "\nCtrl+C pressed. Aborting countdown and releasing inhibition."
echo "Killing systemd-inhibit process... - PID: $inhibit_pid"
kill $inhibit_pid # Kill systemd-inhibit process
exit 1
}
# Function to convert time input to seconds
function convert_to_seconds() {
local input=$1
local time_unit=${input: -1} # Get last character (unit)
local time_value=${input:0:-1} # Get value without unit
local seconds=0
case $time_unit in
"h") seconds=$((time_value * 3600));; # hours to seconds
"m") seconds=$((time_value * 60));; # minutes to seconds
"s") seconds=$time_value;; # seconds
*) echo "Invalid time unit. Please use 'h', 'm', or 's'."; exit 1;;
esac
echo $seconds
}
# Countdown function
function countdown {
secs=$1
while [ $secs -gt 0 ]; do
echo -ne "Time left: $secs\033[0Ks\r"
sleep 1
: $((secs--))
done
echo -e "Time's up!\n"
}
# Main script
clear
echo "Starting countdown..."
# Get countdown time input from user
read -p "Enter countdown time (e.g., 4h, 30m, 120s): " countdown_input
# Convert time input to seconds
countdown_time=$(convert_to_seconds $countdown_input)
# Trap Ctrl+C and call ctrl_c function
trap ctrl_c SIGINT
# Inhibit system sleep
systemd-inhibit --what=sleep --who="" --why="$USER is building something!" bash -c "sleep $countdown_input; systemctl suspend" &
# sleep 3000 &
inhibit_pid=$!
echo "ID of systemd-inhibit process: $inhibit_pid"
# Start countdown
countdown $countdown_time
# Other commands or actions to perform after countdown
echo "Performing post-countdown actions..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment