PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] How to run command in background and also capture the output

 August 15, 2022     background, bash, localhost, output     No comments   

Issue

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
...

Solution

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.


Answered By - pjh
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing