'Can not join bash array when it contains dynamically formed strings
I need to generate SQL statement using bash
This code works fine:
#!/usr/bin/env bash
STRINGS+=("( host = '.example.com' AND name = 'auth.sid' )")
STRINGS+=("( host = '.site.example.test' AND name = 'key' )")
joinByString() {
local separator="$1"
shift
local first="$1"
shift
printf "%s" "$first" "${@/#/$separator}"
}
joinByString ' OR ' "${STRINGS[@]}"
it prints ( host = '.example.com' AND name = 'auth.sid' ) OR ( host = '.site.example.test' AND name = 'key' )
But if STRINGS array is dynamic - it does not work:
MAIN_COOKIES=$(cat <<EOF
.example.com:auth.sid
.site.example.test:key
EOF
)
joinByString() {
local separator="$1"
shift
local first="$1"
shift
printf "%s" "$first" "${@/#/$separator}"
}
declare -a andConditions
while read -r line
do
IFS=':' read -r -a array <<< "$line"
cookie_name="${array[1]}"
cookie_hostname="${array[0]}"
and_condition="( host = '${cookie_hostname}' AND name = '${cookie_name}' )"
andConditions+=($and_condition)
done < <(echo "${MAIN_COOKIES}")
joinByString ' OR ' "${andConditions[@]}"
prints ( OR host OR = OR '.example.com' OR AND OR name OR = OR 'auth.sid' OR ) OR ( OR host OR = OR '.site.example.test' OR AND OR name OR = OR 'key' OR ) - so joinByString function adds $separator near every space character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
