I have the following bash script:

set -m
./cloud_sql_proxy -instances=[project-id]:[region]:[instance-id]=tcp:5432 -credential_file=serviceaccount.json &
sleep 5
node app.js

First, I want the cloud_sql_proxy command to run. After 5 seconds, I also want the node command to run. The first command (cloud_sql_proxy) is a command that keeps running, so a wait does not work here (it keeps waiting).

When the cloud_sql_proxy command is 'ready', it outputs "Ready for new connections". Is there anyway I can "capture" this output, check if it "Ready for new connections", and if so, execute the second command (node)? In that way, I do not longer need the sleep 5 and I'm sure the node command is not running if there is a problem with the cloud_sql_proxy command.

  • 1
    You can redirect the output of cloud_sql_proxy to a file and then grep that file for the required output to check.
    – kaylum
    Commented Jan 22, 2020 at 21:36

1 Answer 1


Since your proxy process runs in the background, the normal ways of capturing output don't work (ex: var=$(echo "test command"))

The easiest way to capture the output you want would be to redirect all output to a file, then check that file for the string you need.

Here's an example:


set -m

# Added output redirection for stdout and stderr
./cloud_sql_proxy --add_your_options_here >filename 2>&1 &

# Wait for up to 5 seconds for the service to be ready.
for attempt in $(seq 1 5); do
    sleep 1
    if grep -q "Ready for new connections" filename; then
    if [[ attempt -eq 5 ]]; then
        echo "Error launching sql proxy - see 'filename' for command output."

node app.js

To view output, cat filename.

This solution should work as long as the file is being truncated every time you run the script. If not, the grep will return true due to "stale" text in the file.

  • Thank you! It works. This is a solution I would never come up with. I was trying to save the output into a file and reading out that file, but it was empty, like you said, it's a background process.
    – Sam Leurs
    Commented Jan 22, 2020 at 22:32
  • 1
    For cleanliness you should probably use mktemp to get a unique filename for use, and then rm the file before running node. It'll still be "open" for as long as the proxy process runs but it'll be automatically cleaned up when the process terminates. Commented Jan 23, 2020 at 0:22
  • @StephenHarris: I added "> filename" to clear the content, but when I open the container and do "cat filename" I still get the output, so that's not working. I'm going to try your approach now.
    – Sam Leurs
    Commented Jan 23, 2020 at 11:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .