-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtd.sh
executable file
·96 lines (84 loc) · 2.67 KB
/
td.sh
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
88
89
90
91
92
93
94
95
96
#!/bin/bash
# Converting seconds to human readable time duration.
# Copyright (c) 2010, 2012 Yu-Jie Lin
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
usage() {
echo "Usage: $(basename "$0") [options] [seconds[ seconds[ seconds[...]]]]
Options:
-a prints all number even they are zeros.
-p[X] padding for numbers. 'X' is the padding character, default is ' '.
-P padding for unit strings.
-h this help message.
Note:
You can \`source $(basename "$0")\` then use \`print_td <seconds>\` in your script.
"
}
units=(second minute hour day)
print_td() {
t=${1#-}
nums=($(($t % 60)) $(($t / 60 % 60)) $(($t / 3600 % 24)) $(($t / 86400)))
result=""
for ((idx=${#units[@]}-1;idx>=0;idx--)) {
((nums[idx] == 0)) && [[ -z $TD_SH_PRINTS_ZEROS ]] && continue;
# Handling Number Padding
if (( nums[idx] < 10 )) && [[ ! -z $TD_SH_NUMB_PADDING ]]; then
result="$result ${TD_SH_NUMB_PADDING}${nums[idx]}"
else
result="$result ${nums[idx]}"
fi
result="$result ${units[idx]}"
# Handling Unit Padding
if ((nums[idx] != 1)); then
result="${result}s"
elif [[ ! -z $TD_SH_UNIT_PADDING ]]; then
result="${result} "
else
result="${result}"
fi
}
[[ -z "$result" ]] && result="0 seconds"
echo "${result# }"
}
shopt -s extglob
TD_SH_PRINTS_ZEROS=
TD_SH_UNIT_PADDING=
TD_SH_NUMB_PADDING=
for arg in "$@"; do
case "$arg" in
?(-)+([[:digit:]]))
print_td "$arg"
;;
-a)
TD_SH_PRINTS_ZEROS="ON"
;;
-P)
TD_SH_UNIT_PADDING="ON"
;;
-p)
TD_SH_NUMB_PADDING=" "
;;
-p?)
TD_SH_NUMB_PADDING=${arg:2:1}
;;
-h)
usage
;;
esac
done