Last active
July 28, 2017 10:02
-
-
Save denistex/508adda28a9dc50d820781ca3d9a52a7 to your computer and use it in GitHub Desktop.
Bash script for automated shutting down if there are no active sessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Copy script to `/etc/cron.hourly/autohalt` (*without extension*). | |
# Log and pid files will be placed in root directory. | |
DELAY=${1:-30} # minutes | |
LOG=${2:-"autohalt.log"} | |
PID=${2:-"autohalt.pid"} | |
function log { | |
echo "[$$][$(date)] $1" >> $LOG | |
} | |
function loop { | |
local STEP=0 | |
while [ $STEP -lt $DELAY ]; do | |
sleep 1m | |
local SESSIONS=$(w -h | wc -l) | |
if [ $SESSIONS -eq 0 ]; then | |
log "No active sessions found on step $STEP, sleeping..." | |
STEP=$((STEP + 1)) | |
else | |
log "$SESSIONS active session(s) found, sleeping..." | |
STEP=0 | |
fi | |
done | |
} | |
function main { | |
log "Starting..." | |
if [ -f $PID ]; then | |
log "Pid file found, exiting..." | |
exit 0 | |
else | |
echo $$ > $PID | |
fi | |
loop | |
log "No active sessions, shutting down..." | |
rm -f $PID | |
halt | |
} | |
main & |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment