-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbash-humanize.sh
executable file
·79 lines (60 loc) · 1.85 KB
/
bash-humanize.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
#!/bin/bash
# A simple script the humanizes the time echo-elapsed
# usage : ./bash-humanize <time_in_seconds>
echo-elapsed () {
if [ $1 -gt 0 ]; then
echo -n "$1 $2 "
fi
}
is_leap_year () {
year=$(date +%Y)
if (( ("$year" % 400) == "0" )) || (( ("$year" %4) == "0" )) && (( ("$year" % 100) != 0 )); then
return 0
else
return 1
fi
}
time-humanize () {
now=$(date +%s)
if [ -z $1 ]; then
in_seconds=now
else
in_seconds=$1
fi
#some time calc constants
minutes_seconds=60
hours_seconds=$(( 60 * $minutes_seconds ))
days_seconds=$(( 24 * $hours_seconds ))
days_month=$(cal -m `date +%m` | grep -v "^$" | tail -1 | grep -o "..$")
months_seconds=$(( $days_month * $days_seconds ))
if is_leap_year; then
year_seconds=$(( 366 * $days_seconds ))
else
year_seconds=$(( 365 * $days_seconds ))
fi
elapsed_seconds=$(( $now - $in_seconds ))
if [ $elapsed_seconds -eq 0 ]; then
echo "now"
return
fi
elapsed_years=$(( $elapsed_seconds / $year_seconds ))
remaining_seconds=$(( $elapsed_seconds % $year_seconds ))
elapsed_months=$(( $remaining_seconds / $months_seconds ))
remaining_seconds=$(( $remaining_seconds % $months_seconds ))
elapsed_days=$(( $remaining_seconds / $days_seconds ))
remaining_seconds=$(( $remaining_seconds % $days_seconds ))
elapsed_hours=$(( $remaining_seconds / $hours_seconds ))
remaining_seconds=$(( $remaining_seconds % $hours_seconds ))
elapsed_minutes=$(( $remaining_seconds / $minutes_seconds ))
remaining_seconds=$(( $remaining_seconds % $minutes_seconds ))
#print the results
echo-elapsed $elapsed_years "years"
echo-elapsed $elapsed_months "months"
echo-elapsed $elapsed_days "days"
echo-elapsed $elapsed_hours "hours"
echo-elapsed $elapsed_minutes "minutes"
echo-elapsed $remaining_seconds "seconds"
echo -n "ago"
echo
}
time-humanize $@