summaryrefslogtreecommitdiffstats
path: root/tools/mtime.sh
blob: c2f9dfa9d2c2dbf8e660ba865e244ef306f01d61 (plain)
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
#!/bin/sh
#
# Utility to portably get a file's modification time
#
# Copyright (C) 2018, 2019  Patrick McDermott
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -u

get_mtime()
{
	local file="${1}"
	shift 1
	local m=
	local d=
	local y=
	local now_m=
	local now_y=

	read m d y <<-EOF
		$(LC_ALL=POSIX ls -l "${file}" | cut -d ' ' -f 6-8)
		EOF
	case "${m}" in
		'Jan')  m=1;; 'Feb')  m=2;; 'Mar')  m=3;; 'Apr')  m=4;;
		'May')  m=5;; 'Jun')  m=6;; 'Jul')  m=7;; 'Aug')  m=8;;
		'Sep')  m=9;; 'Oct') m=10;; 'Nov') m=11;; 'Dec') m=12;;
	esac
	case "${y}" in *':'*)
		read now_m now_y <<-EOF
			$(date '+%m %Y')
			EOF
		now_m="${now_m#0}"
		if [ ${now_m} -ge ${m} ]; then
			y=${now_y}
		else
			y=$((${now_y} - 1))
		fi
	esac

	printf '%d-%02d-%02d\n' ${y} ${m} ${d}
	return 0
}

usage()
{
	printf 'Usage: %s <file>\n' "${0}"
}

main()
{
	if [ ${#} -lt 1 ]; then
		usage >&2
		exit 1
	fi

	get_mtime "${1}"
}

main "${@}"