Home > database >  How to run command in background and also capture the output
How to run command in background and also capture the output

Time:03-05

In the middle of the script, I have a command that exposes the local port with ssh -R 80:localhost:8080 localhost.run I need to execute this command in the background, parse the output and save it into a variable.

The output returns:

Welcome to localhost.run!
...
abc.lhrtunnel.link tunneled with tls termination, https://abc.lhrtunnel.link

Need to capture this part:

https://abc.lhrtunnel.link

As a result something like this:

...
hostname=$(command)
echo $hostname
...

CodePudding user response:

Try this Shellcheck-clean code:

#! /bin/bash -p

hostname=$(ssh ...  \
            | sed -n 's/^.*tunneled with tls termination, //p')
declare -p hostname
  • I'm assuming that you don't really want to background the command that generates the output. You just want to run it in a way that allows its output to be captured and filtered. See How do you run multiple programs in parallel from a bash script? for information about how "background" processes are used for parallel processing.
  • The -n option to sed means that it doesn't print lines from the input unless explicitly instructed to print.
  • s/^.*tunneled with tls termination, //p works on input lines that contain anything followed by the string tunneled with tls termination, . It deletes everything on the line up to the end of that string and prints the result, which hopefully will be the URL that you want.
  • declare -p varname is a much more reliable and useful way to show the value of a variable than using echo.
  • Related