Skip to content

Instantly share code, notes, and snippets.

@creachadair
Last active June 19, 2024 17:07
Show Gist options
  • Save creachadair/1723c052afb964e082ec4000cfeab512 to your computer and use it in GitHub Desktop.
Save creachadair/1723c052afb964e082ec4000cfeab512 to your computer and use it in GitHub Desktop.
Set or refresh a timed shutdown of a machine
#!/usr/bin/env bash
#
# Usage: vm-shutdown.sh [--check|--cancel|--help]
#
# Schedule a shutdown of the system at a time in the future.
# With --check, do not schedule a shutdown, just print the scheduled time.
# With --cancel, cancel a pending shutdown.
#
# Installation:
#
# - Copy this script somewhere in your $PATH.
# - Ensure the script is run on each login, e.g., from .bash_profile.
#
# The default shutdown period is 4 hours; edit "howlong" below to use a
# different period. Run the script explicitly at any time to refresh the
# timeout.
set -euo pipefail
# Location of the scheduled shutdown record (if there is one).
timefile=/run/systemd/shutdown/scheduled
# How long until shutdown (minutes).
howlong=240
whendown() {
if [[ ! -f "$timefile" ]] ; then
echo "no shutdown scheduled"
else
date --date=@"$(head -1 "$timefile" | cut -d= -f2 | rev | cut -c7- | rev)"
fi
}
case "${1:-}" in
(-check|--check|-when|--when)
whendown
exit 0
;;
(-c|-cancel|--cancel)
sudo shutdown --no-wall -c
echo "shutdown cancelled" 1>&2
exit 0
;;
(-h|-help|--help)
echo "Run without arguments to reset shutdown." 1>&2
echo " Use --check to check how long is left until shutdown" 1>&2
echo " Use --cancel to disable a pending shutdown" 1>&2
exit 1
;;
(?*)
echo "Unknown option ${1}" 1>&2
exit 2
;;
esac
sudo shutdown --no-wall +"$howlong" 2>/dev/null
printf "Shutdown at: %s\n" "$(whendown)" 1>&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment