fix using non-local variable
[tee-unique] / appendu-function
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.
8 Append each line to FILE if it does not exist in FILE.
9 Use LINE if specified, else use lines from stdin.
10 Appended lines are output to the terminal.
11
12 -s don't try to use sudo when it would help us read or write the file
13 -- stop processing arguments
14 --help display this message"
15
16 local dosudo=true
17
18 while true; do
19 if [[ $1 == --help ]]; then
20 echo "$help"
21 return
22 elif [[ $1 == -s ]]; then
23 dosudo=false
24 shift
25 elif [[ $1 == -- ]]; then
26 shift
27 break
28 else
29 break
30 fi
31 done
32
33 if [[ ${#@} == 0 ]]; then
34 echo "error: need 1 or more arguments"
35 echo "$help"
36 return 1
37 fi
38
39 local readsudo writesudo x
40 local file="$1"
41 shift
42
43 if [[ -e $file ]]; then
44 [[ -r $file ]] || readsudo=sudo
45 [[ -w $file ]] || writesudo=sudo
46 else
47 local dir="$(dirname "$file")"
48 if [[ -d $dir ]]; then
49 [[ ! -w $dir ]] && writesudo=sudo
50 else
51 echo "appendu error: $dir does not exist"
52 return 1
53 fi
54 fi
55 if ! $dosudo; then
56 readsudo=
57 writesudo=
58 fi
59 if (( $# )); then
60 for x in "$@"; do
61 [[ -e "$file" ]] && $readsudo grep -q "^$x$" "$file" || $writesudo tee -a "$file"<<<"$x"
62 done
63 elif [[ ! -t 0 ]]; then
64 unset IFS
65 while read -r x; do
66 # duplicated from above
67 [[ -e "$file" ]] && $readsudo grep -q "^$x$" "$file" || $writesudo tee -a "$file"<<<"$x"
68 done
69 fi
70 }