add note about license
[small-misc-bash] / isdiff
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to switch
7 # its license to GPL.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23
24 isdiff() {
25 local help="Usage: isdiff [--help|-h] [-v] [-x] FILE1 FILE2
26 Test if FILE1 and FILE2 have the same contents
27
28 Returns 0 for same, 1 for diff, 2 for error.
29
30 -v verbose
31 -r use most reliable checksum available, ie. sha instead of md5"
32
33 local v x y reliable
34 while true; do
35 if [[ $1 == --help ]] || [[ $1 == -[^-]* && $1 == *h* ]]; then
36 echo "$help"
37 return
38 elif [[ $1 == -[^-]* && $1 == *v* ]]; then
39 v=true
40 shift
41 elif [[ $1 == -[^-]* && $1 == *r* ]]; then
42 reliable=true
43 shift
44 else
45 break
46 fi
47 done
48
49 x=($(type -p sha512sum) $(type -p sha256sum) $(type -p sha1sum) $(type -p md5sum))
50 if [[ $reliable ]]; then
51 sumbinary=$x
52 else
53 sumbinary=${x[${#x[@]}-1]}
54 fi
55
56 [[ $sumbinary ]] || {
57 echo "Need 1 of sha512sum sha256sum sha1sum or md5sum for sum() function"
58 return 1
59 }
60 if [[ $# != 2 ]]; then
61 [[ $v ]] && echo Error: need 2 arguments.
62 return 2
63 fi
64 if [[ $v ]]; then
65 x=$($sumbinary < "$1" ) || return 2
66 y=$($sumbinary < "$2" ) || return 2
67 else
68 { x=$($sumbinary < "$1" ) ;} 2>/dev/null || return 2
69 { y=$($sumbinary < "$2" ) ;} 2>/dev/null || return 2
70 fi
71 if [[ $x == "$y" ]]; then
72 return 1 # same
73 else
74 [[ $v ]] && echo "$1" "$2" different.
75 return 0
76 fi
77 }
78 isdiff "$@"