initial commit
[tee-unique] / appendu
1 #!/bin/bash
2 # Copyright (C) 2014 Ian Kelling
3 # This program is under GPL v. 3 or later, see <http://www.gnu.org/licenses/>
4
5 appendu() {
6 local help="Usage: appendu [OPTION]... FILE LINE...
7 Append unique. Append each LINE to FILE if it does not exist in FILE.
8 Appended lines are output to the terminal.
9
10 -s don't try to use sudo when it would help us read or write the file
11 -- stop processing arguments
12 --help display this message"
13
14 local dosudo=true
15
16 while true; do
17 if [[ $1 == --help ]]; then
18 echo "$help"
19 return
20 elif [[ $1 == -s ]]; then
21 dosudo=false
22 shift
23 elif [[ $1 == -- ]]; then
24 shift
25 break
26 else
27 break
28 fi
29 done
30
31 if (( ${#@} < 2 )); then
32 echo "error: need 2 or more arguments"
33 echo "$help"
34 return 1
35 fi
36
37 local readsudo writesudo
38 local file="$1"
39 shift
40
41 if [[ -e $file ]]; then
42 [[ -r $file ]] || readsudo=sudo
43 [[ -w $file ]] || writesudo=sudo
44 else
45 local dir="$(dirname "$file")"
46 if [[ -d $dir ]]; then
47 [[ ! -w $dir ]] && writesudo=sudo
48 else
49 echo "appendu error: $dir does not exist"
50 exit 1
51 fi
52 fi
53 if ! $dosudo; then
54 readsudo=
55 writesudo=
56 fi
57 for x in "$@"; do
58 [[ -e "$file" ]] && $readsudo grep -q "^$x$" "$file" || $writesudo tee -a "$file"<<<"$x"
59 done
60 }
61 appendu "$@"