-1

I want to read only the first line of netstat, i.e. the line that explains what each column means:

Proto  Local Address     Foreign Address  State

However, when I do the following:

netstat | egrep -i "^\s*(tcp|udp)" | { 
  read line
  echo 'Here is the first line ' $line
 }

I only get the first line of connections:

Here is the first line TCP <Local_addr>  <Foreign_addre>  ESTABLISHED

How do I get just that one line?

I am runing Cygwin on Windows 7 machine. Thanks.

makansij
  • 9,303
  • 37
  • 105
  • 183
  • I personally wouldn't use `read` for this purpose - I'd find a way to pull out just that one line and assign it directly to a variable. Example: `line="$(netstat -n | sed -n 2p)"` – iscfrc Jun 28 '15 at 05:18

1 Answers1

1

To read the first output line of any command, such as netstat, into the shell variable line, use:

read -r line < <(netstat| head -n1)

The use head is not necessary here but it speeds things up.

A side-effect of the above is that any leading or trailing whitespace is removed before the line is assigned to line. That is probably an advantage here. If you wanted to preserve the whitespace, use IFS= read -r line < <(netstat| head -n1).

The construct < <(...) is called process substitution. It requires bash or other advanced shell. Note that the space between the two < is essential.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thanks, that was a good explanation. Nothing is placed into "line" when I run this, though. It prints out nothing. – makansij Jun 27 '15 at 22:18
  • @Sother Does `netstat | head -n1` run by itself produce any output? – John1024 Jun 27 '15 at 22:44
  • `netstat | head -nX`, where X is any positive integer, properly prints out the appropriate line. However, I am unable to retrieve it via `echo` when run in a bash script. – makansij Jun 27 '15 at 23:08
  • This works. However, my netstat outputs in the 1st line `Active Internet connections`, so get the `nTH` line i would to use: `netstat | sed -n 2p` (e.g. for the second line - what contais: `Proto Recv-Q Send-Q Local Address Foreign Address (state)` – kobame Jun 27 '15 at 23:14
  • @Sother At the command line, please run `read -r line < <(netstat| head -n1); echo "line=$line"` and tell me what you see. – John1024 Jun 27 '15 at 23:17
  • I see `line=` which is interesting. – makansij Jun 28 '15 at 06:41