Created
June 1, 2018 17:04
-
-
Save pesterhazy/9020617ade9c93c3cccd9748f76dbe01 to your computer and use it in GitHub Desktop.
Run multiple commands from the command line, with shared STDOUT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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