gotosleep

Bash script with some environment checking that ACPI suspends a Linux box. Developed on Slackware 14, no idea if it’ll work on any other *nix box but would assume it would, perhaps with a little hacking.

#!/usr/bin/env bash

# Script that tests various situations that the user
# may wish to be aware of before it suspends the machine.
# Written on Slackware 14 as a replacement for the now
# non-functioning acpitool slackbuild.

# SSH session test
sshsess=`ps -ef | grep ssh | egrep -v '(sshd|grep)' | wc -l`

function killssh {
for sshpid in `ps -ef | grep ssh | egrep -v '(sshd|grep)' | awk '{print $2}'`; do printf "Killing ssh session with pid $sshpid\n" && kill -9 $sshpid; done
}

if [ "$sshsess" -gt 0 ]; then
	printf "User, Session, PID\n"
	printf "=====================================================\n"
	ps -ef | grep ssh | egrep -v '(sshd|grep)' | awk '{print $1" "$8" "$9" "$2}'
	printf "=====================================================\n"
	printf "You have $sshsess ssh session(s) open, kill? [y/n] "
	read killans
	if [[ "$killans" = "Y" || "$killans" = "y" ]]; then
		killssh
		printf "\n"
		sleep 1
	else
		printf "\nOK dude, leaving those bad boys open\n\n"
	fi
else
	printf "No ssh sessions found\n"
fi

# Editor test - no kill option, too dangerous! Only checks CLI editors.
# You can add your editor to the regex if it's not there like this:
# ...joe|YOUREDITOR)' If its name is short you may want to do
# something like the regex for vi and ed.
editorsess=`ps -ef | egrep '(vi[^a-l|n-z]|nano|emacs|pico|elvis|[^a-z]ed[^a-z]|joe)' | grep -v grep | wc -l`

if [ "$editorsess" -gt 0 ]; then
	printf "You have the following editor session(s) open:\n"
	printf "=====================================================\n"
	ps -ef | egrep '(vi[^a-l|n-z]|nano|emacs|pico|elvis)' | grep -v grep | awk '{print $8"\t"$1"\t"$2}'
	printf "=====================================================\n"
	printf "Go ahead and kill them, press any key to suspend when you're done"
	read
else
	printf "No open editor sessions found\n"
fi

#Test if superuser, if not give login then suspend

if [ "$LOGNAME" != "root" ];
then
	printf "You aren't root are you?\n"
	sudo printf "ZZZzzzzzzz...\n" && echo mem >/sys/power/state
else
	printf "ZZZzzzzzzz....\n"
	echo mem >/sys/power/state
fi