Victor Ferreira
Victor Ferreira

Reputation: 6449

How to transform the output of a command in a list of arguments in BASH?

there

I need to pass multiple arguments to a docker command, but I wanted this string of arguments to be built interactively and not by hand. In my specific problem, I want to get all the environment variables in this machine and set each one of them as a build-arg argument.

For example, if the env variables are

ENV_VAR1=ENV_VALUE1
ENV_VAR2=ENV_VALUE2
ENV_VAR3=ENV_VALUE3

I want to build a string like this

docker build --build-arg ENV_VAR1=ENV_VALUE1 --build-arg ENV_VAR2=ENV_VALUE2 --build-arg ENV_VAR1=ENV_VALUE1 .`

I was wondering how to wrap this repetition in a bash script something like this (please this is just a pseudocode):

docker build $(FOREACH get_output_of_env() AS $env DO `--build-arg $env` END) .

Is that anyhow possible?

Thanks in advance

Upvotes: 0

Views: 270

Answers (2)

petrus4
petrus4

Reputation: 614

#!/bin/sh

cat > args < EOF
#!/bin/sh
EOF
env -0 >> args
sed -i s'@^@--build-arg @g' args
tr '\n' ' '
sed -i s'@^@docker build@' args

Then just execute "args" as another shell script. I admit that I haven't tested this, but I can't see too many reasons why it shouldn't work.

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141235

Use an array:

dockerargs=()
for i in ENV_VAR1 ENV_VAR2 ENV_VAR3; do
     dockerargs+=(--build-arg "$i=${!i}")
done
docker build "${dockerargs[@]}" ...

If you really want to use how to iterate over env and do for i in $(compgen -e)

Upvotes: 2

Related Questions