# HG changeset patch # User Franz Glasner # Date 1725129070 -7200 # Node ID 527d38d0003d0e45e8b91de546d8a3294225188b # Parent 0b7b7b49bb310a2691b582cab3eb91ccb3f5cc7c array.sh: FIX: Use really proper escaping when appending values to an array diff -r 0b7b7b49bb31 -r 527d38d0003d share/local-bsdtools/array.sh --- a/share/local-bsdtools/array.sh Sat Aug 31 18:17:09 2024 +0200 +++ b/share/local-bsdtools/array.sh Sat Aug 31 20:31:10 2024 +0200 @@ -50,6 +50,37 @@ #: +#: Quote the given input to be safely used in evals with "Dollar-Single Quotes" +#: +#: Args: +#: $1: the value to be quoted +#: +#: +#: From FreeBSD's :manpage:`sh(1)`: +#: +#: Dollar-Single Quotes +#: +#: Enclosing characters between ``$'`` and ``'`` preserves the literal +#: meaning of all characters except backslashes and single quotes. +#: +#: A backslash introduces a C-style escape sequence. +#: Most important here: +#: +#: ``\\`` +#: Literal backslash +#: +#: ``\'`` +#: Literal single-quote +#: +_quote_for_eval_dsq() { + printf "%s" "${1}" \ + | /usr/bin/sed -e $'s/\\\\/\\\\\\\\/g' -e $'s/\'/\\\\\'/g' + # escape a backslash escape a single quote + # ' # make Emacs happy for correct syntax highlighting +} + + +#: #: Create a new array. #: #: It is assumed that the array does not exist already. @@ -159,8 +190,15 @@ fi _l1=$((${_l} + 1)) + + # # Set value - eval ${_gvrname}_${_l1}="\"${_value}\"" + # Escape properly: use $' ' and escape any backslashes and single quotes. + # + eval ${_gvrname}_${_l1}=\$\'"$(_quote_for_eval_dsq "${_value}")"\' + # the implementation below line does not escape properly + # eval ${_gvrname}_${_l1}="\"${_value}\"" + # Set new array length eval ${_gvrname}__=${_l1} } @@ -368,7 +406,7 @@ #: #: Returns: #: - 0 (truish) if the argument value is found within the given array -#: and index constraints +#: and index constraints #: - 1 (falsy) otherwise #: array_find() {