-
-
Save ootada/e80b6d7fb86acdcda75d77eb7ade364c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -eu | |
| # bash version: | |
| define(){ IFS=$'\n' read -r -d '' ${1} || true; } | |
| # 'do not touch last newline' bash version: | |
| #define(){ IFS= read -r -d '' ${1} || true; } | |
| # 'loop' version that also works with ksh: | |
| function define2 { typeset a o=; while IFS= read -r a; do o+="$a"$'\n'; done; o=${o%?}; eval "$1=\$o"; } | |
| # 'do not touch last newline' ksh version: | |
| #function define2 { typeset a o=; while IFS= read -r a; do o+="$a"$'\n'; done; eval "$1=\$o"; } | |
| # p.s. 'eval' might be a security risk here only if you're using dynamic user supplied variable name to define, it will not evaluate heredoc strings. | |
| # usage example: | |
| define VAR <<'EOF' | |
| abc 'asdf " \$ $ \n $'\n' | |
| $(dont-exec ute-this) | |
| foo " bar " ' ' | |
| `bad bad `` | |
| EOF | |
| # also same for ksh version: | |
| define2 VAR2 <<'EOF' | |
| abc 'asdf " \$ $ \n $'\n' | |
| $(dont-exec ute-this) | |
| foo " bar " ' ' | |
| `bad bad `` | |
| EOF | |
| # tests - compare output: | |
| echo '---------' | |
| echo "$VAR" | |
| echo '---------' | |
| echo "$VAR2" | |
| echo '---------' | |
| # test the symbol counts, should be the same | |
| echo " 5 18 78" | |
| echo "$VAR" |wc | |
| echo "$VAR2"|wc | |
| # should not leave global variables defined | |
| echo ${o-o is unset: ok} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment