File: pause.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright (c) 2026 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the "Software"), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # pause [options...] [words...]
  27 #
  28 # Show a prompt and wait for a key press, no need for the enter key. You can
  29 # show a custom prompt using the arguments, same way as the `echo` command.
  30 #
  31 # If no words are given for the prompt, a default message is used instead.
  32 #
  33 # The options are, available both in single and double-dash versions
  34 #
  35 #   -h, -help       show this help message
  36 #   -t, -timeout    wait only up to the number of seconds given
  37 
  38 
  39 wait_key='dd if=/dev/tty bs=512 count=1'
  40 
  41 case "$1" in
  42     -h|--h|-help|--help)
  43         awk '/^# +pause /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  44         exit 0
  45     ;;
  46 
  47     -t|--t|-timeout|--timeout)
  48         if [ $# -lt 2 ]; then
  49             printf "forgot the timeout seconds\n" >&2
  50             exit 1
  51         fi
  52         if echo "$2" | grep -q '[^0-9]'; then
  53             printf "use a round positive number for the seconds\n" >&2
  54             exit 1
  55         fi
  56         wait_key="timeout -f $2 ${wait_key}"
  57         shift
  58         shift
  59     ;;
  60 esac
  61 
  62 [ "$1" = '--' ] && shift
  63 
  64 if [ $# -eq 0 ]; then
  65     printf "Press (almost) anything on your keyboard to continue..."
  66 else
  67     printf "%s" "$*"
  68 fi
  69 
  70 prev="$(stty -g)"
  71 trap "stty \"${prev}\"; printf \"\\n\"; exit" 0
  72 stty raw -echo
  73 
  74 ${wait_key} > /dev/null 2> /dev/null