Created
January 18, 2021 18:30
-
-
Save ohnit/7094a68084ba89c1b7d7912cb0af47d0 to your computer and use it in GitHub Desktop.
Turn on 'Do Not disturb' for a time period on macOS
This file contains hidden or 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
#!/bin/bash | |
# See `showUsage` for desciption | |
# requires `gsed` via `brew install gnu-sed` | |
# requires `dnd` via `npm install --global do-not-disturb-cli` | |
function showUsage() { | |
cat <<EOS | |
Usage: $(basename "${0}") "<time_description>" | |
Turns on 'Do Not disturb' for a time period on macOS | |
time_description examples: | |
- "1h 30m" | |
- "1 hour 30 minutes 15 seconds" | |
- "20 min" | |
- "2m" | |
EOS | |
} | |
function durationToSeconds () { | |
# modified from https://stackoverflow.com/a/58617630/2443614 | |
set -f | |
local value | |
local fallback | |
normalize () { echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d "\"\\\'" | sed 's/ *y\(ear\)\{0,1\} */y /g; s/ *d\(ay\)\{0,1\} */d /g; s/ *h\(our\)\{0,1\} */h /g; s/ *m\(in\(ute\)\{0,1\}\)\{0,1\} */m /g; s/ *s\(ec\(ond\)\{0,1\}\)\{0,1\} */s /g; s/\([ydhms]\) s/\1/g'; } | |
value=$(normalize "$1") | |
fallback=$(normalize "$2") | |
if (echo "$value" | grep -q -v '^[-+*/0-9ydhms ]\{0,30\}$'); | |
then | |
>&2 echo Invalid duration pattern \""$value"\" | |
else | |
if [ "$value" = "" ]; then | |
[ "$fallback" != "" ] && durationToSeconds "$fallback" | |
else | |
local template | |
sedtmpl () { echo "s/\([0-9]\+\)$1/(0\1 * $2)/g;"; } | |
template="$(sedtmpl '\( \|$\)' 1) $(sedtmpl y '365 * 86400') $(sedtmpl d 86400) $(sedtmpl h 3600) $(sedtmpl m 60) $(sedtmpl s 1) s/) *(/) + (/g;" | |
echo "$value" | gsed "$template" | bc | |
fi | |
fi | |
set +f | |
} | |
if ((!${#})); then | |
showUsage; | |
exit 1; | |
fi | |
seconds="$(durationToSeconds "$@")" | |
echo "Setting 'Do Not Disturb' until $(gdate --date="+$seconds seconds" '+%T')" | |
dnd on | |
sleep "$seconds" | |
dnd off | |
echo "'Do Not Disturb' ended" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment