From 2f3c7f86ac866d8517340ef1ecceff326290cf15 Mon Sep 17 00:00:00 2001 From: Augusto Moura Date: Mon, 19 Oct 2020 19:09:16 -0300 Subject: [PATCH] change some trimming functions to subshells to prevent options overriding --- README.md | 41 ++++++++++++----------------------------- 1 file changed, 12 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 1fd0155..5e7082d 100644 --- a/README.md +++ b/README.md @@ -171,8 +171,10 @@ without leading/trailing white-space and with truncated spaces. **Example Function:** ```sh +# Run function as a subshell (note the parenthesis) +# To prevent overriding outside shell options and environment variables # shellcheck disable=SC2086,SC2048 -trim_all() { +trim_all() ( # Usage: trim_all " example string " # Disable globbing to make the word-splitting below safe. @@ -185,10 +187,7 @@ trim_all() { # Print the argument list as a string. printf '%s\n' "$*" - - # Re-enable globbing. - set +f -} +) ``` **Example Usage:** @@ -269,15 +268,13 @@ This is an alternative to `cut`, `awk` and other tools. **Example Function:** ```sh -split() { +# Run function as a subshell (note the parenthesis) +# To prevent overriding outside shell options and environment variables +split() ( # Disable globbing. # This ensures that the word-splitting is safe. set -f - # Store the current value of 'IFS' so we - # can restore it later. - old_ifs=$IFS - # Change the field separator to what we're # splitting on. IFS=$2 @@ -292,13 +289,7 @@ split() { # Print each list value on its own line. printf '%s\n' "$@" - - # Restore the value of 'IFS'. - IFS=$old_ifs - - # Re-enable globbing. - set +f -} +) ``` **Example Usage:** @@ -323,17 +314,15 @@ $ split "1, 2, 3, 4, 5" ", " **Example Function:** ```sh -trim_quotes() { +# Run function as a subshell (note the parenthesis) +# To prevent overriding outside shell options and environment variables +trim_quotes() ( # Usage: trim_quotes "string" # Disable globbing. # This makes the word-splitting below safe. set -f - # Store the current value of 'IFS' so we - # can restore it later. - old_ifs=$IFS - # Set 'IFS' to ["']. IFS=\"\' @@ -351,13 +340,7 @@ trim_quotes() { # Print the quote-less string. printf '%s\n' "$*" - - # Restore the value of 'IFS'. - IFS=$old_ifs - - # Re-enable globbing. - set +f -} +) ``` **Example Usage:**