Skip to content

Instantly share code, notes, and snippets.

@andsens
Last active October 26, 2022 11:38
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 andsens/ca6d3e0374f91618194ee5a011dddaef to your computer and use it in GitHub Desktop.
Save andsens/ca6d3e0374f91618194ee5a011dddaef to your computer and use it in GitHub Desktop.
Bash notebook for nifty things
#!/usr/bin/env bash
# wait for backgrounded jobs and propagate $?>0.
local pid
while read -r pid; do wait "$pid"; done < <(jobs -p)
# wait for backgrounded jobs, propagate $?>0, and exit early on failure.
while (($(jobs -p | wc -l) > 0)); do
if wait -n; then
:
else
ret=$?
jobs -p | xargs -n1 kill 2>/dev/null
wait
exit $ret
fi
done
# Benchmark call() in ms
_THEN=$(date +%s.%N)
call()
printf "fn(): %ss\n" "$(echo "($(date +%s.%N) - $_THEN)" | bc)" >&2
# Output a stacktrace (https://stackoverflow.com/a/62757929/339505)
stacktrace() {
local level=1 line file func linetxt
while read -r line func file < <(caller $level); do
linetxt=$(sed -n "${line}p" "${file}" | sed 's/ *//')
linetxt=${linetxt# *}
printf "[%d] %s:%d %s(): %s\n" "$level" "${file#$PWD/}" "$line" "$func" "$linetxt"
((level++))
done
}
# Get relative timings of all lines in a script
bash -x script.sh 2>&1 | ts -i %.s
# Parallelize work and append results to array (https://stackoverflow.com/a/64783182/339505)
readarray -td $'\0' -O"${#results[@]}" build_env < <(
while IFS= read -r target <&3; do (
do_work
printf "\0"
) & done 3< <(get_work)
while read -r pid; do wait "$pid"; done < <(jobs -p)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment