Reputation: 13
The person who wrote the follow bash script has left and I need to figure out the meaning of the follow bash script he wrote. This script is executed in a docker container before running some test cases which requires a running mysql instance.
I guess it is about starting a mysql server, but I am not exactly sure about the exact meaning of each statement in this script.
echo -n "Loading [+"
( echo "SHOW TABLES;" | mysql mysql 2>/dev/null 1>/dev/null ) || \
run-mysqld 2>/dev/null 1>/dev/null &
while ! ( echo "SHOW TABLES;" | mysql mysql 2>/dev/null 1>/dev/null ) ;
do
echo -n +
sleep 1
done
echo "] Done."
I had to figure out this because our bitbucket pipeline recently gets stuck and timeout when running this script (previously it was fine). Thanks in advance.
Upvotes: 1
Views: 125
Reputation: 42999
This sequence attempts to run SHOW TABLES
through mysql, ignoring any output. If mysql fails (because mysqld isn't running), it starts mysqld to run in background.
( echo "SHOW TABLES;" | mysql mysql 2>/dev/null 1>/dev/null ) || \
run-mysqld 2>/dev/null 1>/dev/null &
The second part of the code just waits for mysqld to start up, which is signaled by the following code exiting 0:
( echo "SHOW TABLES;" | mysql mysql 2>/dev/null 1>/dev/null )
If mysqld doesn't come up with a single attempt, the second part of the code would run forever. Looks like that's what happened.
The simplest way to make this code free from hanging is to put a limit on how long we sleep:
max_sleep=15
sleep=0
while ! ( echo "SHOW TABLES;" | mysql mysql 2>/dev/null 1>/dev/null ) ;
do
echo -n +
sleep 1
((sleep++ > max_sleep)) && { echo "Failed to start mysqld] Error."; exit 1; }
done
echo "] Done."
exit 0
Upvotes: 3