I'm trying to create a bash script that will automatically install and configure a MySQL server. The script is calling the following shell script, mysql_init.sh
:
#! /bin/sh
export MYSQL_HOME=$PWD
mysqld \
--defaults-file=$MYSQL_HOME/my.cnf \
--lc-messages-dir="<lc-messages-dir-path>" \
--datadir=$MYSQL_HOME/data \
--basedir=$MYSQL_HOME \
--pid-file=$MYSQL_HOME/mysql.pid \
--socket=$MYSQL_HOME/socket \
--port=3307 \
--initialize
The init script will then initialise the MySQL server and print a temporary random password (which I've made up for illustration) at the bottom, like so:
2021-10-01T13:05:06.437633Z 0 [Warning] [MY-010139] [Server] Changed limits: max_open_files: 4096 (requested 8161)
2021-10-01T13:05:06.437646Z 0 [Warning] [MY-010142] [Server] Changed limits: table_open_cache: 1967 (requested 4000)
2021-10-01T13:05:06.438228Z 0 [System] [MY-013169] [Server] /<path-to-mysqld>/mysqld (mysqld 8.0.26) initializing of server in progress as process 33740
2021-10-01T13:05:06.440561Z 0 [Warning] [MY-010339] [Server] Using pre 5.5 semantics to load error messages from <lc-messages-dir-path>. If this is not intended, refer to the documentation for valid usage of --lc-messages-dir and --language parameters.
2021-10-01T13:05:06.471924Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2021-10-01T13:05:08.924829Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2021-10-01T13:05:11.915605Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1 is enabled for channel mysql_main
2021-10-01T13:05:11.916199Z 0 [Warning] [MY-013746] [Server] A deprecated TLS version TLSv1.1 is enabled for channel mysql_main
2021-10-01T13:05:12.020289Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: abc12345789
I want to grab that password to use to login to the server in my top-level script. However, when I try:
./mysql_init.sh | tail -n1
./mysql_init.sh > output_file.txt
It doesn't work. Regardless of what I do, all of the messages are printed to the terminal, and I'm not able to capture any of the lines, nor the last line.
How can I capture the last line of this output?
CodePudding user response:
Could be just a case of redirecting errors to output and so add 2>&1 to the end of you script call ......
./mysql_init.sh 2>&1 | tail -n1
./mysql_init.sh 2>&1 > output_file.txt