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.

NewUser
  • 1
  • 1
  • (1) [Quote right](https://unix.stackexchange.com/a/131767/108618). (2) Compare [this question](https://superuser.com/q/1628497/432690) and read my answer there. – Kamil Maciorowski Jun 28 '22 at 17:35
  • 1
    Really need to parse variables in a file that is yet ready ? Why not simply : --env-file=.env ? Also, if you source .env you get all variabes set. – Thibault LE PAUL Jul 01 '22 at 20:27

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
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
RudiC
  • 8,889
  • 2
  • 10
  • 22
  • 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