Background:
I'm working on a project in which a server is started at a random available port. The server is started by a command:
node server.js
Once the server is ready and starts serving on an available port, it outputs (along with a bunch of other logs) the complete server URL (including port number) on stdout in the following form:
Server started! Listening on URL: http://localhost:12927
This server process keeps running until you manually kill it (and keeps printing some other logs).
Actual problem:
I'm writing a script to start the server and then listen to its output. As soon as I get the message something like "Server started! Listening on URL: [SERVER_URL]"
, I want to store this SERVER_URL
in a variable and process later in the script (e.g. open a browser for automation testing).
What I've tried:
Having only a very basic understanding of Bash, I've tried the following options (of course, after researching on SE):
I researched a bit about using
grep
with regex. This works pretty well if I do it manually (i.e. not storing it to variable and just piping from anecho
command.SERVER_URL=$(node server.js | grep -m 1 -ohP 'Server started! Listening on URL: \K([^\s$]*)')
However, it kinda blocks on this line, probably it's waiting for the node server to get killed. My requirement is clear: I want to populate SERVER_URL from the server's output without waiting for it beyond the point it spits out that URL on stdout.
I also fiddled around a bit with redirection and process substitution. I learnt that the pipe actually waits for the source process to get completed. I've tried to do the following with redirection, but it's not working:
SERVER_URL=$(node server.js >&3 | grep -m 1 -ohP 'Server started! Listening on URL: \K([^\s$]*)')
It is throwing some weird "Unhandled 'error' event" exception (Error: write EPIPE).
Any help is appreciated. Thanks!
man cat
to see thecat
documentation and useq
to quit. Googlelinux man pages
for links. Here's a freely available book that I like: The Linux Command Line – jrw32982 Aug 29 '20 at 16:24