Skip to content

Instantly share code, notes, and snippets.

@instanceofme
Last active December 20, 2015 04:09
Show Gist options
  • Save instanceofme/6069264 to your computer and use it in GitHub Desktop.
Save instanceofme/6069264 to your computer and use it in GitHub Desktop.
Proof-of-concept script that begins synchronously then goes asynchronous. Meant to be called via SSH, executes some instructions synchronously, launches a long asynchronous task (e.g. download), wait a few seconds to ensure that said taks didn't fail immediately, then ends the SSH connection. See http://serverfault.com/questions/524738/remote-sy…
#! /usr/bin/env bash
function closefd() {
exec 0>&- # close stdin
exec 0<&-
exec 1>&- # close stdout
exec 1<&-
exec 2>&- # close stderr
exec 2<&-
}
if [[ $1 == "-do" ]]; then
closefd # release SSH connection, part 2/2 (child)
# asynchronous task
sleep 30 &&
echo $2 >/tmp/ok
else
# preliminary-synchronous-commands &&
nohup $0 -do $1 &
sleep 5 # ensure it didn't immediately fail
if ! kill -0 $!; then
echo "Cannot find PID"
exit 1
else
echo "PID found, exiting"
closefd # release SSH connection, part 1/2 (parent)
exit 0
fi
fi
@instanceofme
Copy link
Author

&& (chains commands only if they are successful / have a return status of 0) can be omitted when

set -e

is specified before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment