Skip to content

Instantly share code, notes, and snippets.

@wernerb
Created June 29, 2014 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wernerb/14beb8101dd27e66bca8 to your computer and use it in GitHub Desktop.
Save wernerb/14beb8101dd27e66bca8 to your computer and use it in GitHub Desktop.
Executes commands asynchronously while keeping stdout/stderr. Does not use tail -f, stops when the command stops. Works in POSIX shells.
############
# Executes commands asynchronously while keeping stdout/stderr.
# If the shell quits or fails then the script can be started again and it
# will read in stdout again from the beginning and continue.
#
# Author: Werner Buck
############
# Command to execute asynchronously.
TOEXECUTE="./test.sh"
# Where you'd like stdout to be stored.
STDOUT="stdout"
# Where you'd like stderr to be stored.
STDERR="stderr"
# Where the pid can be read
PIDFILE="pid"
#Checks if pid is there. If it is, we don't run the command.
if test ! -f "$PIDFILE"; then
nohup "$TOEXECUTE" > "$STDOUT" 2> "$STDERR" & echo $! > "$PIDFILE"
fi
#The following reads and continues reading stdout
offset=0
while kill -0 $(cat "$PIDFILE") >/dev/null 2>&1
do
sleep 1
cursize=$(du -b "$STDOUT" | cut -f1)
if test $offset -eq 0; then
tail -q -c "+0" "$STDOUT" | head -q -c "$cursize"
else
tail -q -c "+$offset" "$STDOUT" | head -q -c $(expr "$cursize" + 1 - "$offset")
fi
offset=$(expr "$cursize" + 1 )
done
tail -q -c "+$offset" stdout
rm -f "$PIDFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment