Skip to content

Instantly share code, notes, and snippets.

@plesner plesner/

Last active Aug 29, 2015
What would you like to do?
Sh script for connecting to a machine while pinging it with a wake-on-lan package in the background every minute
set -e
# How often to send wake-on-lan pokes.
# Mac address of the machine to poke.
# Host address to connect to.
# When run as [ poke] it loops around indefinitely poking
# the machine.
if [ "$1" = "poke" ]; then
while true; do
wakeonlan $MAC_ADDR > /dev/null
# Spawn the poke job and record its PID. Be careful here -- if the
# recursive call should for some reason not park in the loop above
# this script effectively becomes a fork-bomb. This happened.
$0 poke &
# Ensure that the poke job is killed when this script exits.
cleanup_on_exit() {
# Silence kill since, depending on how the signals bounce, this may be called
# more than once. Also, the poke job may die before we exit.
kill $POKE_PID > /dev/null 2>&1
# Do cleanup on normal exit and interrupt (ctrl-C).
trap cleanup_on_exit EXIT INT
# Wait for at least one successful ping before trying to
# connect. Waking up can take a while and mosh gives up quickly if the
# destination doesn't respond.
if ! ping -c1 $HOSTNAME > /dev/null; then
echo "Host is currently unavailable; waiting for it to appear."
while ! ping -c1 $HOSTNAME > /dev/null; do
# Finally we've seen a successful ping to the machine. Mosh it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.