Skip to content

Instantly share code, notes, and snippets.

@simple10
Last active August 29, 2015 14:08
Show Gist options
  • Save simple10/eb92e78d1cd062727a70 to your computer and use it in GitHub Desktop.
Save simple10/eb92e78d1cd062727a70 to your computer and use it in GitHub Desktop.
Shell runner for capturing output and exit code.
#!/bin/sh
# Capture node output and status code for passing commands back to shell.
# This snippet is useful for running a node script that outputs a command
# to run after it exits in situations where node is conflicting with
# tty or environment settings.
main() {
local tempout; tempout=`mktemp -t tmp.out` || exit 1
local statusfile; statusfile=`mktemp -t tmp.status` || exit 1
local exitcode;
# Send stdout to $tempout for later parsing
{ node --harmony cli.js $@; echo $? > $statusfile; } | tee $tempout
exitcode=`cat $statusfile`
# Run script in background and wait for it to exit
# eval node --harmony cli.js $@ > $tempfile &
# for job in `jobs -p`; do
# # Set exitcode if not 0
# wait $job || let "exitcode=$?"
# done
# This is a bit hacky but it works.
# For commands that need to run in the current shell,
# the CLI prints "EXEC::$CMD" and returns code=2.
if [ "$exitcode" = 2 ]; then
local output; output=`tail -n1 $tempout`
if [ ! "${output##EXEC::*}" ]; then
output=`echo $output | sed -e 's/^EXEC:://'`
printf "\nRUNNING COMMAND >> $output\n"
eval $output
fi
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment