Launch process from Bash script in the background, then bring it to foreground Launch process from Bash script in the background, then bring it to foreground bash bash

Launch process from Bash script in the background, then bring it to foreground


Job control using fg and bg are only available on interactive shells (i.e. when typing commands in a terminal). Usually the shell scripts run in non-interactive shells (same reason why aliases don't work in shell scripts by default)

Since you already have the PID stored in a variable, foregrounding the process is same as waiting on it (See Job Control Builtins). For example you could just do

wait "$pid"

Also what you have is a basic version of coproc bash built-in which allows you get the standard output messages captured from background commands. It exposes two file descriptors stored in an array, using which one can read outputs from stdout or feed inputs to its stdin

coproc fdPair interactive_command 

The syntax is usually coproc <array-name> <cmd-to-bckgd>. The array is populated with the file descriptor id's by the built-in. If no variable is used explicitly, it is populated under COPROC variable. So your requirement can be written as

coproc fdPair interactive_command IFS= read -r -u "${fdPair[0]}" firstLineprintf '%s\n' "$firstLine"