d04f587b62928d5ab9744bdccac5e890eb07b895
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.
17 local help="Usage: [-h|--help ] [-v] [SECTION_NAME] FILE
18 Create/edit a #comment delimited section of a file
20 Reads STDIN for the contents of the section. Without SECTION_NAME, it
21 acts on a global unnamed section. cedit is short for config edit.
25 local s
diff name init
26 local file_dir
="$(dirname "$file")"
31 -h|
--help) echo "$help"; return ;;
34 if [[ $1 == -v ]]; then
38 if (( $# == 2 )); then
44 local file_name
="${file##*/}"
46 local begin
="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
47 local end
="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
49 if [[ ! -e $file_dir ]]; then
50 if ! mkdir
-p $file_dir; then
52 $s mkdir
-p $file_dir ||
return 1
55 if [[ ! -e $file ]]; then
57 if ! $s touch $file; then
59 $s touch $file ||
return 1
63 [[ -w $file ]] || s
=sudo
67 local temp
="$(mktemp -d)/$file_name"
70 local in_section
=false
71 while IFS
= read -r line
; do
72 if [[ $line == $begin ]]; then
75 if ! $in_section; then
76 printf '%s\n' "$line" >> $file
78 if [[ $line == $end ]]; then
84 IFS
= read -d '' -n 1 -r init
86 $s tee -a "$file" >/dev
/null
<<<"$begin"
87 printf '%s' "$init" |
$s tee -a "$file" >/dev
/null
88 $s tee -a "$file" >/dev
/null
89 $s tee -a "$file" >/dev
/null
<<<"$end"
95 echo "New file $file:"
98 elif type -t diff &>/dev
/null
; then
99 diff=$
(diff -u "$temp" "$file")
102 if (( $ret == 0 )); then
103 echo "No changes made to $file"
107 echo "backup of original at $temp"
108 echo diff -u "$temp" "$file":
112 diff=$
(cmp "$temp" "$file")