Bash "[email protected]" does not substitute variable

All we need is an easy explanation of the problem, so here it is.

I am sorry because this probably has been asked, but I cannot google these special characters properly.

I have the following script.sh:

#!/bin/bash

export c=23;

"[email protected]"

And when I call it with:

(export a=231; export b=45; ./script.sh echo "$a, $b, $c")

The variable $c does not appear in the output:

231, 45,

How can I create a passthrough script that adds extra variables to the executed command?


Edit again for the full context:

The usage is that I have a docker container. The dockerfile gets the COMMIT_HASH at build time. Then I want to call java app.jar (for container run) and this running process should have the COMMIT_HASH variable configured.

So in the Dockerfile, I have something like this now:

RUN echo "#!/bin/bash \n java -Dapp.info.commit-hash=\"${COMMIT_HASH}\" -jar /app.jar \"\[email protected]\"" > ./entrypoint.sh

...

ENTRYPOINT ["./entrypoint.sh"]

As you can see, with this setup I cannot configure arguments for the jar. But I cannot find out how to be able to create the full command outside the container and have the variables substituted into it.

This is why, ideally, I would like to have a script that makes it available to specify extra variables, but also have the variables configured as default.

That is why the final script (now without the Dockerfile usage) would look something like this:

#!/bin/bash

export COMMIT_HASH=a982321bc232d;

"[email protected]"

Then merging them together with:

# read from a .env file or something - these are dynamic values
export PORT=8081;
export FRONTEND_URL=http://example.com;

java -Dapp.info.commit-hash="${COMMIT_HASH}" -Dserver.port="${PORT}" -jar /app.jar --FRONTEND_URL="${FRONTEND_URL}"

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You’ll need to escape the sigil for $c when invoking the script, and in the script eval "[email protected]" to get a 2nd round of variable expansion.

$ cat script.sh
#!/bin/bash

export c=23;

eval "[email protected]"
$ (export a=231; export b=45; bash -x ./script.sh echo "$a, $b, \$c")
+ export c=23
+ c=23
+ eval echo '231, 45, $c'
++ echo 231, 45, 23
231, 45, 23

Or, single quote the code to send to the script and let the script’s shell expand all the variables:

$ (export a=231; export b=45; bash -x ./script.sh 'echo "$a, $b, $c"')
+ export c=23
+ c=23
+ eval 'echo "$a, $b, $c"'
++ echo '231, 45, 23'
231, 45, 23

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply