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