hotmeatballsoup
hotmeatballsoup

Reputation: 595

Populating variable in a script other than by means of env var

Please note: even though this question mentions MySQL and Docker, it really has nothing to do with either and should be answerable by any knowledgable bash scripter.


Rusty on my bash scripting here. I'm looking at the official MySQL 8.0 Dockerfile and see that it calls and runs a bash script called docker-entrypoint.sh. Looking at that script, it appears to (conditionally) run a snippet of code that creates a database, if it doesn't already exist:

if [ "$MYSQL_DATABASE" ]; then
  echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}"
  mysql+=( "$MYSQL_DATABASE" )
fi

I'm wondering where that script is expecting the MYSQL_DATABASE variable be populated from. If it was expecting MYSQL_DATABASE to be an optional environment variable, I would have expected (from my admittedly rusty recollection) the if-conditional to look something like:

if [ -z "$MYSQL_DATABASE" ]; then
  ...
fi

I suppose it could be that MYSQL_DATABASE is expected to be a runtime argument to the script, but I'm leaning away from this as a viable option because the Dockerfile isn't passing any args to the script's invocation.

Can anyone help clue me in as to how I can populate MYSQL_DATABASE with the name of a DB (such as "my_db") so that when this script runs, the DB is created for me?

Upvotes: 0

Views: 49

Answers (1)

IMSoP
IMSoP

Reputation: 97648

As far as a shell script is concerned, an environment variable is just a variable that happens to be inherited from the environment, it doesn't change the behaviour of that variable.

So to understand what the code does, you don't need to know which "type" of variable it is, only that by that point in the code, there might be a variable with that name. You then need to know this fact about the [ (aka test) command:

STRING: equivalent to -n STRING

and

-n STRING: the length of STRING is nonzero

So all [ "$MYSQL_DATABASE" ] means is "is the length of the $MYSQL_DATABASE variable more than zero at this point in the code?"

Whether this variable is expected "before" the script runs (e.g. preset as an environment variable) or calculated "inside" the script, you can only find out by reading through.

Upvotes: 2

Related Questions