2

在 bash 中,我想启动我的程序(gollum)并使用 stderr 的一部分(端口号)作为另一个程序的参数。我将 stderr 重定向到 stdout 并使用 grep 和 sed 过滤输出。我在标准输出中得到结果:

gollum -p0 2>&1|  sed  -n -e "s/.*port=//p"

它返回“56343”并继续运行,因为 gollum 是服务器。

但是,如果我想将其用作另一个程序的参数(即 echo,但我想稍后使用它来启动带有端口号的 Internet 导航器)与 xargs 它不起作用。

gollum -p0 2>&1|  sed  -n -e "s/.*port=//p" | xargs -n1  echo  

什么都没发生。你知道为什么,或者你有另一个想法来做同样的事情。

谢谢您的帮助。

4

1 回答 1

2

This is easy to do if you don't want your server to keep running in the background. If you do, one approach is to use process substitution:

#!/bin/bash
#      ^^^^- not /bin/sh; needed for >(...) syntax

gollum -p0 > >(
  while IFS= read -r line; do
    # start a web browser here, etc.
    [[ $line = *"port="* ]] && echo "${line##*port=}"
    # ...for instance, could also be:
    # open "http://localhost:${line##*port=}/"
  done
) 2>&1 &

...if you want to read only the first line containing port=, then break out of the loop in the handler, and handle the rest of stdin before it exits (this is as easy as using cat >/dev/null).

于 2016-09-29T22:46:33.570 回答