Skip to content

Instantly share code, notes, and snippets.

@ootada
Last active April 12, 2024 11:42
Show Gist options
  • Select an option

  • Save ootada/e80b6d7fb86acdcda75d77eb7ade364c to your computer and use it in GitHub Desktop.

Select an option

Save ootada/e80b6d7fb86acdcda75d77eb7ade364c to your computer and use it in GitHub Desktop.
#!/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