'Shell script stop running with background process

I'm trying to run the mysqld in bg to execute some command with the mysql client but my script stop running when I fg my process, here is the script I use

set -m
daemon="/usr/bin/mysqld --user=mysql --console --skip-name-resolve --skip-networking=0 $@"
$daemon &
exec echo "Test"
exec fg %1

I'm not an expert for shell scripting, I check in some website and I found this way to execute my command.



Solution 1:[1]

No. The script stop after the exec echo "Test". The exec replaces the current process (the shell script) with the command after it. You can verify this with:

daemon="/usr/bin/mysqld --user=mysql --console --skip-name-resolve --skip-networking=0 $@"
$daemon &
exec echo "Test"
echo "Second Test"
exec fg %1

The solution is simple: don't use exec.

BTW: it is unclear why you would want to do a fg in a shell script. fg has only a function in interactive shells, not in scripts.

Solution 2:[2]

Ok Thank you a lot, I found this command to do what i want, and it work

sh /scripts/run.sh & sleep 2 \
        && mysql -utest -ppass mydb < \
        /docker-entrypoint-initdb.d/mydb.sql

For the foreground process I didn't know that fg only work in interactive thank you for your precision.

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 Ljm Dullaart
Solution 2