2 # Copyright (C) 2016 Ian Kelling
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 cedit
() { # [-v] [section_name] FILE
18 local s
diff name init
19 local file_dir
="$(dirname "$file")"
23 if [[ $1 == -v ]]; then
27 if (( $# == 2 )); then
33 local file_name
="${file##*/}"
35 local begin
="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
36 local end
="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
38 if [[ ! -e $file_dir ]]; then
39 if ! mkdir
-p $file_dir; then
41 $s mkdir
-p $file_dir ||
return 1
44 if [[ ! -e $file ]]; then
46 if ! $s touch $file; then
48 $s touch $file ||
return 1
52 [[ -w $file ]] || s
=sudo
56 local temp
="$(mktemp -d)/$file_name"
59 local in_section
=false
60 while IFS
= read -r line
; do
61 if [[ $line == $begin ]]; then
64 if ! $in_section; then
65 printf '%s\n' "$line" >> $file
67 if [[ $line == $end ]]; then
73 IFS
= read -d '' -n 1 -r init
75 $s tee -a "$file" >/dev
/null
<<<"$begin"
76 printf '%s' "$init" |
$s tee -a "$file" >/dev
/null
77 $s tee -a "$file" >/dev
/null
78 $s tee -a "$file" >/dev
/null
<<<"$end"
84 echo "New file $file:"
87 elif type -t diff &>/dev
/null
; then
88 diff=$
(diff -u "$temp" "$file")
91 if (( $ret == 0 )); then
92 echo "No changes made to $file"
96 echo "backup of original at $temp"
97 echo diff -u "$temp" "$file":
101 diff=$
(cmp "$temp" "$file")