Skip to content

Instantly share code, notes, and snippets.

@pesterhazy
Created June 1, 2018 17:04
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 pesterhazy/9020617ade9c93c3cccd9748f76dbe01 to your computer and use it in GitHub Desktop.
Save pesterhazy/9020617ade9c93c3cccd9748f76dbe01 to your computer and use it in GitHub Desktop.
Run multiple commands from the command line, with shared STDOUT
#!/usr/bin/env bash
set -euo pipefail
syntax() {
cat <<EOF
Evaluate multiple commands passed as arguments.
Commands are separated with `--` (double dash). If it doesn't precede `--`, the final
command will be run in the foreground, with stdin connected to the terminal. All other
commands are sent to the background.
Example:
doall run-daemon -p 8080 -- bash -c "sleep 2 && nc localhost 8080"
EOF
}
invoke() {
"$@" &
pids+=($!)
}
invoke_all() {
pids=()
xs=()
for arg in "$@"
do
case "$arg" in
--)
invoke "${xs[@]}"
xs=()
;;
*)
xs+=("$arg")
;;
esac
done
if [[ ${#xs[@]} -ne 0 ]]; then
"${xs[@]}"
else
wait "${pids[@]}"
fi
}
trap "exit" INT TERM
trap "kill 0" EXIT
invoke_all "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment