0

I have a script called render.sh that looks like this:

#!/usr/bin/env bash

if [[ -f "${ENVIRONMENT}.yaml" ]]; then ENV_YAML="-f ${ENVIRONMENT}.yaml" fi

set -x helm3 template "$SERVICE_NAME" . --namespace="$NAMESPACE"
${ENV_YAML:-}
--set environment="$ENVIRONMENT"

It's sourced in a larger script twice:

SERVICE_NAME=a
NAMESPACE=b
ENVIRONMENT=foo
source render.sh

other code

SERVICE_NAME=a NAMESPACE=b ENVIRONMENT=bar source render.sh

The output looks like this:

++ helm3 template a . --namespace=b -f foo.yaml --set environment=foo
...
++ helm3 template a . --namespace=b '-f bar.yaml' --set environment=bar

In the second execution, something is adding quotes. I know bash has a few different ways of automatically adding quotes like ${VAR@Q} and "$@", but none of them seem to be in use.

Is there a mode in bash that would automatically add quotes during parameter expansion?

Leo
  • 101
  • 2
    If you want -f and ${ENVIRONMENT}.yaml to be treated as separate arguments, you should probably be using an array rather than a simple string assignment. See for example How can we run a command stored in a variable? – steeldriver Feb 28 '23 at 16:28
  • 1
    I could not reproduce on my machine. However this code might be buggy: if the .yaml file does not exist, it will use the previous one, which may be what you want, or not... – Totor Feb 28 '23 at 16:29
  • Good tip on the array syntax! I am trying to avoid changing the script in this case, so I'm still curious about what could cause the change in how bash expands the parameters between the two runs – Leo Feb 28 '23 at 17:29
  • 2
    Is something modifying IFS in between? If it's changed so that it doesn't contain the space, the value from ${ENV_YAML:-} wouldn't be split. – ilkkachu Feb 28 '23 at 19:03
  • Note that it's not about "adding quotes" as such, but about not splitting the value. (Bash's set -x output does include quotes so that the output is aligns with shell syntax and is unambiguous, though.) The quotes produced by ${VAR@Q} are actually there in the value, while "$@" can be said to be similar to "$1" "$2" but is probably better thought of as just giving the positional parameters as separate fields/arguments without other changes or additions. – ilkkachu Feb 28 '23 at 19:07
  • Consider e.g. VAR="abc def"; set -- uvw xyz; printf "<%s>\n" "${VAR@Q}" "$@", where <'abc def'> outputs with quotes, but <uvw>, <xyz> don't. – ilkkachu Feb 28 '23 at 19:11
  • Also I'm not sure the :- in ${ENV_YAML:-} does much, as it only tells the shell to use the empty string if the variable value is the empty string (or unset). – ilkkachu Feb 28 '23 at 19:13

0 Answers0