forked from stay-sharp/hosts_for_google_service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckhosts.sh
executable file
·85 lines (71 loc) · 1.76 KB
/
checkhosts.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
#!/bin/bash
# https://github.com/racaljk/hosts
EOL_BREAK=0
FORMAT_BREAK=0
DATE_BREAK=0
chk_eol()
{
printf "\e[33;1mCheck line endings:\e[0m\n"
if file "$1" | grep -q "CRLF"; then
printf "\e[31mDOS line endings have appeared, "
printf "it must be coverted now!\e[0m\n\n"
EOL_BREAK=1
else
printf "\e[32mAll is well!\e[0m\n\n"
fi
}
# Check TAB, leading and trailing whitespace.
chk_format()
{
printf "\e[33;1mCheck hosts format:\e[0m\n"
# Filter all hosts records.
grep -Pv "^\s*#" "$1" | grep -P "(\d+\.){3}\d+" > 1.swp
# Detect trailing whitespace.
grep -P "\s+$" "$1" >> 1.swp
# Filter good hosts records.
grep -Pv "^\s*#" "$1" | grep -P "^(\d+\.){3}\d+\t\w" > 2.swp
if ! diff 1.swp 2.swp > 0.swp; then
printf "\e[31mhosts format mismatch! "
printf "The following rules should be normalized:\e[0m\n"
cat 0.swp; printf "\n"
FORMAT_BREAK=1
else
printf "\e[32mAll is well!\e[0m\n\n"
fi
rm -f 0.swp 1.swp 2.swp
}
cmp_date()
{
if [ "$1" != "$2" ]; then
printf "\e[31mhosts date mismatch, last modified "
printf "is $1, but hosts tells "
printf "$2\e[0m\n\n"
DATE_BREAK=1
else
printf "\e[32mAll is well!\e[0m\n\n"
fi
}
chk_date()
{
local sys_date=$(date +%F)
local commit_date=$(git log --date=short "$1" |
grep -Pom1 "\d{4}-\d{2}-\d{2}")
local in_file=$(grep -Po "\d{4}-\d{2}-\d{2}" "$1")
printf "\e[33;1mCheck hosts date:\e[0m\n"
# check if hosts file changes.
if git diff --exit-code "$1" &> /dev/null; then
# hosts file is not changed.
cmp_date "$commit_date" "$in_file"
else
# hosts file is being editing, and has not been committed.
cmp_date "$sys_date" "$in_file"
fi
}
if [ -z "$1" ]; then
echo "Usage: $0 [file]"
exit 4
fi
chk_eol "$1"
chk_format "$1"
chk_date "$1"
exit $(( $EOL_BREAK + $FORMAT_BREAK + $DATE_BREAK ))