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/modify a section in a config file
20 The section is #comment delimited. Reads STDIN for the contents of the
21 section. Without SECTION_NAME, it acts on a global unnamed
22 section. cedit is short for config edit.
26 local s
diff name init
27 local file_dir
="$(dirname "$file")"
32 -v) verbose
=true
; shift ;;
33 -h|
--help) echo "$help"; return ;;
36 if (( $# == 2 )); then
42 local file_name
="${file##*/}"
44 local begin
="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
45 local end
="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
47 if [[ ! -e $file_dir ]]; then
48 if ! mkdir
-p $file_dir; then
50 $s mkdir
-p $file_dir ||
return 1
53 if [[ ! -e $file ]]; then
55 if ! $s touch $file; then
57 $s touch $file ||
return 1
61 [[ -w $file ]] || s
=sudo
65 local temp
="$(mktemp -d)/$file_name"
68 local in_section
=false
69 while IFS
= read -r line
; do
70 if [[ $line == $begin ]]; then
73 if ! $in_section; then
74 printf '%s\n' "$line" >> $file
76 if [[ $line == $end ]]; then
82 IFS
= read -d '' -n 1 -r init
84 $s tee -a "$file" >/dev
/null
<<<"$begin"
85 printf '%s' "$init" |
$s tee -a "$file" >/dev
/null
86 $s tee -a "$file" >/dev
/null
87 $s tee -a "$file" >/dev
/null
<<<"$end"
93 echo "New file $file:"
96 elif type -t diff &>/dev
/null
; then
97 diff=$
(diff -u "$temp" "$file")
100 if (( $ret == 0 )); then
101 echo "No changes made to $file"
105 echo "backup of original at $temp"
106 echo diff -u "$temp" "$file":
110 diff=$
(cmp "$temp" "$file")