~tardypad/dotfiles

ref: 00c0c349a1b8960152233f11caa9ea1a40e395a3 dotfiles/files/scripts/shell/loop -rwxr-xr-x 1.6 KiB
00c0c349 — Damien Tardy-Panis Add presentation mode to mako to hide notifications 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/bin/sh

init_variables() {
  COMMAND=${0##*/}

  RUN_COMMAND=
  COUNT=
  INTERVAL=0
  TIME=
}

parse_command_line() {
  while getopts c:i:t: OPT; do
    case "${OPT}" in
      c) COUNT="${OPTARG}" ;;
      i) INTERVAL="${OPTARG}" ;;
      t) TIME="${OPTARG}" ;;
      ?) exit_error ;;
    esac
  done

  shift $(( OPTIND - 1 ))

  RUN_COMMAND="$*"
}

validate_command_line() {
  if [ -z "${COUNT}" ] && [ -z "${TIME}" ]; then
    exit_error 'you must specify at least -c or -t options'
  fi

  case "${COUNT}" in
    *[!0-9]*) exit_error 'count must be an integer' ;;
  esac

  case "${TIME}" in
    *[!0-9]*) exit_error 'time must be an integer' ;;
  esac

  case "${INTERVAL}" in
    *[!0-9.]*) exit_error 'interval must be an number' ;;
  esac

  if [ -z "${RUN_COMMAND}" ]; then
    exit_error 'no command to run'
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  exit 1
} >&2

current_time_sec() {
  # values with leading 0 are interpreted as octals
  # which leads to issue with "08" and "09"
  CUR_HOURS=$( date +%H )
  CUR_MINUTES=$( date +%M )
  CUR_SECONDS=$( date +%S )
  echo $((
    ${CUR_HOURS#0} * 3600 + ${CUR_MINUTES#0} * 60 + ${CUR_SECONDS#0}
  ))
}

loop_command() {
    [ -n "${TIME}" ] && END_TIME=$(( $( current_time_sec ) + TIME ))

    RUN_COUNT=1

    while true; do
      [ -n "${COUNT}" ] && [ "${RUN_COUNT}" -gt "${COUNT}" ] && return 0

      i="${RUN_COUNT}" eval "${RUN_COMMAND}"

      RUN_COUNT=$(( RUN_COUNT + 1 ))

      [ -n "${TIME}" ] && [ "$( current_time_sec )" -ge "${END_TIME}" ] && return 0

      sleep "${INTERVAL}"
    done
}

init_variables
parse_command_line "$@"
validate_command_line

loop_command