2 # Copyright (C) 2014 Ian Kelling
3 # This program is under GPL v. 3 or later, see <http://www.gnu.org/licenses/>
6 local help="Usage: appendu [OPTION]... FILE [LINE_SET]...
10 A LINE_SET is one or more lines. Append LINE_SET to FILE if it does not exist in
11 FILE. If no LINE_SET argument is given, read lines from stdin, and treat each
12 as a single LINE_SET. Appended text is output to the terminal.
14 -s don't try to use sudo when it would help us read or write the file
15 -- stop processing arguments
16 --help display this message"
18 local readsudo writesudo x
strings string
22 if [[ $1 == --help ]]; then
25 elif [[ $1 == -s ]]; then
28 elif [[ $1 == -- ]]; then
36 if [[ ${#@} == 0 ]]; then
37 echo "error: need 1 or more arguments"
46 local file_exists
=false
47 if [[ -e $file ]]; then
49 [[ -r $file ]] || readsudo
=true
50 [[ -w $file ]] || writesudo
=sudo
52 local dir
="$(dirname "$file")"
53 if [[ -d $dir ]]; then
54 [[ ! -w $dir ]] && writesudo
=sudo
56 echo "appendu error: $dir does not exist"
65 if (( $# == 0 )); then
75 # fix files with no newline at the end.
76 # the following command won't work right on them.
77 # e = run script, $a\ means append following text, but there is none,
78 # so sed only does what it always does when it was supposed to modify a file,
79 # which is append a newline if there was none.
81 # this removes any trailing newline in the var, so we add it back on,
82 # because we want a consistent ending to match
85 file_content="$(sudo cat "$file")
88 file_content="$(<"$file")
91 # we aren't using regex because we want to match
strings,
92 # but we also want our match to start at the beginning of a line,
93 # or the beginning of the file, and to end at a line ending.
94 # So we do some slick bash to match this.
99 for string
in "${strings[@]}"; do
100 [[ $file_content != $start"$string"$end ]] && $writesudo tee -a "$file"<<<"$string"
103 for string
in "${strings[@]}"; do
104 $writesudo tee -a "$file"<<<"${strings[@]}"