- if [[ ! -e $file ]]; then
- exists=false
- if ! $s touch $file; then
- s=sudo
- $s touch $file || return 2
- fi
+ fi
+
+ [[ -w $file ]] || s=sudo
+
+
+ local in_section=false
+ if $exists; then
+ local tailn=1
+ local temp="$(mktemp -d)/$file_name"
+ cp "$file" "$temp"
+ cp /dev/null "$file"
+ while IFS= read -r line; do
+ tailn=$(( tailn + 1 ))
+ if [[ $line == "$begin" ]]; then
+ in_section=true;
+ break
+ fi
+ printf '%s\n' "$line" >> $file
+ done < "$temp"
+ fi
+
+ IFS= read -d '' -n 1 -r init
+ if [[ $init ]]; then
+ $s tee -a "$file" >/dev/null <<<"$begin"
+ printf '%s' "$init" | $s tee -a "$file" >/dev/null
+ $s tee -a "$file" >/dev/null
+ $s tee -a "$file" >/dev/null <<<"$end"
+ fi
+
+ if $exists && $in_section; then
+ while IFS= read -r line; do
+ if [[ $line == "$begin" ]]; then
+ in_section=true;
+ fi
+ if ! $in_section; then
+ printf '%s\n' "$line" >> $file
+ fi
+ if [[ $line == $end ]]; then
+ in_section=false;
+ fi
+ done < <(tail -n +$tailn "$temp")
+ fi
+
+
+ if ! $exists; then
+ ret=1
+ if $verbose; then
+ echo "New file $file:"
+ cat "$file"