From e10d1165102a3709d608e09c5970ce643945bf69 Mon Sep 17 00:00:00 2001 From: William Melody Date: Thu, 21 Nov 2019 19:07:05 -0800 Subject: [PATCH] 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 --- hosts | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/hosts b/hosts index dac89f2..77a6a1e 100755 --- a/hosts +++ b/hosts @@ -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" \