Handle platform-specific `sed -i` requirements.

`sed -i` on macOS requires an extension, but on Linux that extension can
cause errors. Use a platform check to only include the extension on
macOS.

resolves gh-5
This commit is contained in:
William Melody 2019-11-21 19:07:05 -08:00
parent 060306f28b
commit e10d116510
1 changed files with 18 additions and 12 deletions

30
hosts
View File

@ -56,6 +56,20 @@ export _SPACE_=$' '
export _TAB_SPACE_="${_TAB_}${_SPACE_}"
export _TAB_SPACE_CC_="[${_TAB_SPACE_}]"
# $SED_I_ARG
#
# `sed -i` takes an extension on macOS, but that extension can cause errors in
# GNU `sed`.
#
# https://stackoverflow.com/q/43171648
# http://stackoverflow.com/a/16746032
if sed --help >/dev/null 2>&1
then # GNU
export SED_I_ARG="-i"
else # macOS
export SED_I_ARG="-i ''"
fi
###############################################################################
# Debug
###############################################################################
@ -811,9 +825,7 @@ disable() {
printf "Disabling:\\n%s\\n" "${_targets}"
# -i '' - in place edit. BSD sed requires extension argument, for GNU
# it's optional. More info: http://stackoverflow.com/a/16746032
sed -i '' \
sed "${SED_I_ARG}" \
-e "s/${_regex_ip}/\\#disabled: \\1/g" \
-e "s/${_regex_commented_hostname}/\\#disabled: \\1/g" \
-e "s/${_regex_hostname}/\\#disabled: \\1/g" \
@ -907,9 +919,7 @@ enable() {
printf "Enabling:\\n%s\\n" "${_targets}"
# -i '' - in place edit. BSD sed requires extension argument, for GNU
# it's optional. More info: http://stackoverflow.com/a/16746032
sed -i '' \
sed "${SED_I_ARG}" \
-e "s/${_regex_ip}/\\1/g" \
-e "s/${_regex_commented_hostname}/\\1/g" \
-e "s/${_regex_hostname}/\\1/g" \
@ -1113,18 +1123,14 @@ remove() {
done
fi
# Regular Expression Notes
#
# -i '' - in place edit. BSD sed requires extension argument, for GNU
# it's optional. More info: http://stackoverflow.com/a/16746032
if ((_is_search_pair))
then
sed -i '' \
sed "${SED_I_ARG}" \
-e "/${_regex_ip_hostname_commented}/d" \
-e "/${_regex_ip_hostname}/d" \
"${HOSTS_PATH}"
else
sed -i '' \
sed "${SED_I_ARG}" \
-e "/${_regex_ip}/d" \
-e "/${_regex_commented_hostname}/d" \
-e "/${_regex_hostname}/d" \