0

I am trying to read some values from a file, save them in bash variables, and run docker by passing the values as environment variables. The file's structure is as follows:

DB_NAME=db
ROOT_PASS=root123
USER_NAME=dev
USER_PASS=dev123

And the code is simply like this:

ROOT_PASS=$(sed -nr '/ROOT_PASS=(\d*)/p' .env | cut -d '=' -f 2)
USER_NAME=$(sed -nr '/USER_NAME=(\d*)/p' .env | cut -d '=' -f 2)
USER_PASS=$(sed -nr '/USER_PASS=(\d*)/p' .env | cut -d '=' -f 2)
DB_NAME=$(sed -nr '/DB_NAME=(\d*)/p' .env | cut -d '=' -f 2)

echo -e $USER_NAME echo -e $USER_PASS echo -e $DB_NAME docker volume ls

docker run --rm
--name init-mysql
-v mysql-data:/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=$ROOT_PASS
-e MYSQL_USER=$USER_NAME
-e MYSQL_PASSWORD=$USER_PASS
-e MYSQL_DATABASE=$DB_NAME
-d mysql:latest && docker exec init-mysql echo $MYSQL_ROOT_PASSWORD

As a result of running this script, I am expecting to see the value of $MYSQL_ROOT_PASSWORD printed on the screen, but it only echoes an empty line (hence, my root user has an empty password). What am I doing wrong? How should I pass the bash variables' value to the docker environment variables?

PS: I know about docker-compose.yml, but, here, I have to use this method.

1 Answers1

0

Looks like it's working for me:

ROOT_PASS=$(sed -nr '/ROOT_PASS=(\d*)/p' .env | cut -d '=' -f 2)
echo $ROOT_PASS 
root123

Show the xtrace (set -x) of the docker command execution.

As the file structure allows for immediate sourceing, why don't you? You'll also want to set the allexport option beforehand so the variables be automatically exported to the environment upon assignment for docker to inherit them:

$ set -o allexport
$ . ./.env
$ echo "$ROOT_PASS"
root123
$ echo "$USER_NAME"
dev
$ printenv USER_NAME
dev
$ echo "$USER_PASS"
dev123
RudiC
  • 8,969
  • MIght be worth pointing out that that /ROOT_PASS=(\d*)/p doesn't make sense. It's equivalent to grep ROOT_PASS=. Also that cut -d = -f 2 won't work when the password contains =. – Stéphane Chazelas Jun 28 '22 at 18:05