'Get docker mysql root password in a variable

I created a mysql docker container mysqlcontainer using following command:

docker exec -it mysqlcontainer -d mysql/mysql-server

I run docker logs mysqlcontainer and get the following:

[Entrypoint] GENERATED ROOT PASSWORD: FB=?ySG5,3#@kur&,Wj459fk2Gy2C_O8

[Entrypoint] ignoring /docker-entrypoint-initdb.d/*

[Entrypoint] MySQL init process done. Ready for start up.
2022-04-22T07:49:23.295242Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld:   

I want to put this generated root password into a variable so that I can use this variable in shell script.

I used the following command to get password but how can I put the password into a variable

docker logs mysqlcontainer 2>&1 | grep GENERATED
[Entrypoint] GENERATED ROOT PASSWORD: FB=?ySG5,3#@kur&,Wj459fk2Gy2C_O8


Solution 1:[1]

For those not familiar with awk, this is a non awk version of the solution. Also declaring and using a variable in one instruction is discouraged by shellcheck.net, I prefer separating the instructions

MYVAR=$(docker logs mysqlcontainer 2>&1 | grep 'GENERATED ROOT PASSWORD' | cut -f5 -d" ")
export MYVAR

Solution 2:[2]

When you say you want the password in a variable, I assume that you mean a shell variable. If so, you can do something like this

export myvar=$(docker logs mysqlcontainer 2>&1 | awk '/GENERATED ROOT PASSWORD/ {print $5}')

then

echo $myvar

should give you the password.

It works by looking for the string 'GENERATED ROOT PASSWORD' in the logs and setting the variable to the 5th word in that line.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 franzisk
Solution 2 Hans Kilian