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 Returns 1 if the file is modified by this command, 2 or higher
23 The section is #comment delimited. Reads STDIN for the contents of the
24 section. Without SECTION_NAME, it acts on a global unnamed
25 section. cedit is short for config edit.
30 local s
diff name init
31 local file_dir
="$(dirname "$file")"
37 -b) backup
=true
; shift ;;
38 -v) verbose
=true
; shift ;;
39 -h|
--help) echo "$help"; return ;;
42 if (( $# == 2 )); then
48 local file_name
="${file##*/}"
50 local begin
="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
51 local end
="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
53 if [[ ! -e $file_dir ]]; then
54 if ! mkdir
-p $file_dir; then
56 $s mkdir
-p $file_dir ||
return 2
59 if [[ ! -e $file ]]; then
61 if ! $s touch $file; then
63 $s touch $file ||
return 2
67 [[ -w $file ]] || s
=sudo
70 local in_section
=false
73 local temp
="$(mktemp -d)/$file_name"
76 while IFS
= read -r line
; do
77 tailn
=$
(( tailn
+ 1 ))
78 if [[ $line == "$begin" ]]; then
82 printf '%s\n' "$line" >> $file
86 IFS
= read -d '' -n 1 -r init
88 $s tee -a "$file" >/dev
/null
<<<"$begin"
89 printf '%s' "$init" |
$s tee -a "$file" >/dev
/null
90 $s tee -a "$file" >/dev
/null
91 $s tee -a "$file" >/dev
/null
<<<"$end"
94 if $exists && $in_section; then
95 while IFS
= read -r line
; do
96 if [[ $line == "$begin" ]]; then
99 if ! $in_section; then
100 printf '%s\n' "$line" >> $file
102 if [[ $line == $end ]]; then
105 done < <(tail -n +$tailn "$temp")
112 echo "New file $file:"
115 elif type -t diff &>/dev
/null
; then
116 diff=$
(diff -u "$temp" "$file")
119 echo "backup of original at $temp"
120 echo diff -u "$temp" "$file":
123 # echo "No changes made to $file"
126 # for systems like openwrt which don't have diff
127 diff=$
(cmp "$temp" "$file")
133 if ! $backup && $exists; then