Skip to content

Instantly share code, notes, and snippets.

@rynkowsg
Created February 24, 2023 02:37
Show Gist options
  • Save rynkowsg/e0b6278c070f7a091b5afab1e2ed52e9 to your computer and use it in GitHub Desktop.
Save rynkowsg/e0b6278c070f7a091b5afab1e2ed52e9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
yes_or_no() {
while true; do
printf "%s [y/n]: " "$*"
read -r yn
case $yn in
[Yy]*) return 0 ;;
[Nn]*) return 1 ;;
esac
done
}
declare -a on_exit_items
on_exit() {
for i in "${on_exit_items[@]}"; do
eval "$i"
done
}
add_on_exit() {
local -r n=${#on_exit_items[*]}
on_exit_items[$n]="$*"
# set the trap only the first time
if [[ $n -eq 0 ]]; then
trap on_exit EXIT
fi
}
# $1 - id
trap_demo() {
local id="$1"
local tmp_dir
tmp_dir=$(mktemp -d -t "dotfiles-$(date +%Y%m%d_%H%M%S)-XXXXXXXX")
add_on_exit rm -rf "${tmp_dir}" \&\& echo "removed ${tmp_dir}"
echo "doing important stuff id=$id"
sleep 1
yes_or_no "Continue?" || return
echo "doing more stuff id=$id"
sleep 1
}
main() {
trap_demo 1
trap_demo 2
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment