It's easier with zsh:
From your scalar variable containing a ,-separated list:
DOMAINS="domain1.tld,domain2.tld"
split on , into an array:
domains=( ${(s[,])DOMAINS} )
zip a opt=( -d ) array with it:
opt=( -d )
./example-script.sh ${opt:^^domains}
If ./example-script.sh supports -ddomain1.tld in addition to -d domain1.tld, you can skip the intermediary array and use:
./example-script.sh -d$^domains
In bash, you could use a loop:
IFS=, # split on ,
set -o noglob # disable glob
domains=( $DOMAINS ) # split+glob
args=()
for domain in "${domains[@]}"; do
args+=( -d "$domain" )
done
./example-script.sh "${args[@]}"
Or you could generate code in the shell syntax with:
IFS=, # split on ,
set -o noglob # disable glob
domains=( $DOMAINS ) # split+glob
if [ "${#domains[@]}" -gt 0 ]; then
printf -v args ' -d %q' "${domains[@]}"
else
args=
fi
shell_code="./example-script.sh$args"
eval -- "$shell_code"
If ./example-script.sh supports -ddomain1.tld in addition to -d domain1.tld, you could also do:
IFS=, # split on ,
set -o noglob # disable glob
domains=( $DOMAINS ) # split+glob
./example-script.sh "${domains[@]/#-d}"
Where we prepend -d to each element of the $domains array.
Standard sh doesn't have arrays nor read -A/-a and standard printf doesn't have %q (and the implementations that support it as an extension don't always generate sh-compatible quoting), but you could use the first bash approach above and "$@" in place of an array:
IFS=, # split on ,
set -o noglob # disable glob
set --
for domain in $DOMAINS; do # split+glob
set -- "$@" -d "$domain"
done
./example-script.sh "$@"
Another option is to call awk to do the splitting and generate sh-compatible code:
eval "./example-script.sh$(
LC_ALL=C awk -v q="'" '
function shquote(s) {
gsub(q, q "\\\\" q q, s)
return q s q
}
BEGIN {
n = split(ENVIRON["DOMAINS"], domains, ",")
for (i = 1; i <= n; i++)
printf " -d %s", shquote(domains[i])
}'
)"
DOMAINSis an environment variable (exported)? Usually, if you want to store many separate things in a variable, you use an array, e.g.domains=(domain1.tld domain2.tld).DOMAINSis env variable added to a Docker container - Container only hasshshell, sozshoptions won't work. Thanks for the replies so far! will have to look into them to see what would work given these constraints.