From 181560bbbf9a1957000a040f0a47ca4aca5d294f Mon Sep 17 00:00:00 2001 From: Devin Teske Date: Sun, 17 Jun 2018 06:03:48 +0000 Subject: [PATCH] sysrc.subr: Fix handling of files with missing newline at EOF PR: bin/203435 Reported by: Andreas Sommer MFC after: 1 week X-MFC-to: stable/11 Sponsored by: Smule, Inc. --- usr.sbin/bsdconfig/share/sysrc.subr | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/usr.sbin/bsdconfig/share/sysrc.subr b/usr.sbin/bsdconfig/share/sysrc.subr index 950089ab3eb..4d27c2047c7 100644 --- a/usr.sbin/bsdconfig/share/sysrc.subr +++ b/usr.sbin/bsdconfig/share/sysrc.subr @@ -559,6 +559,13 @@ f_sysrc_set() # If not found, append new value to last file and return. # if [ "$not_found" ]; then + # Add a newline if missing before appending to the file + awk 'BEGIN { wc = 0 } NR == 1 { + (cmd = "wc -l " FILENAME) | getline + close(cmd) + wc = $1 + } END { exit wc != NR }' "$file" || + echo >> "$file" || return $? echo "$varname=\"$new_value\"" >> "$file" return $? fi @@ -606,8 +613,11 @@ f_sysrc_set() # # Operate on the matching file, replacing only the last occurrence. # + # Use awk to ensure LF at end of each line, else files without ending + # LF will trigger a bug in `tail -r' where last two lines are joined. + # local new_contents retval - new_contents=$( tail -r $file 2> /dev/null ) + new_contents=$( awk 1 "$file" 2> /dev/null | tail -r ) new_contents=$( echo "$new_contents" | awk -v varname="$varname" \ -v new_value="$new_value" "$f_sysrc_set_awk" ) retval=$?