How to fetch only limited output of a command in Linux terminal?

Issue

I am trying to fetch only top 5 lines of a command. The usual way would be to use head option but it is not working for all the commands. Below are some examples.

  1. head option works for nping command.
    rajkumar:~/automation$ nping | head -5
    Nping 0.7.60 ( https://nmap.org/nping )
    Usage: nping [Probe mode] [Options] {target specification}
    
    TARGET SPECIFICATION:
      Targets may be specified as hostnames, IP addresses, networks, etc.
    rajkumar:~/automation$ nping | wc -l
    119
    rajkumar:~/automation$
  1. However, head option doesn’t work for iperf3 command which expects some predefined command line arguments and outputs error if it doesn’t find them. How to overcome this?
    rajkumar:~/automation$ iperf3 | head -5
    Usage: iperf [-s|-c host] [options]
           iperf [-h|--help] [-v|--version]
    
    Server or Client:
      -p, --port      #         server port to listen on/connect to
    
    >>>>>>>>>>>>  TRIMMED OUTPUT  <<<<<<<<<<<<<<<<<
    
    [KMG] indicates options that support a K/M/G suffix for kilo-, mega-, or giga-
    
    iperf3 homepage at: http://software.es.net/iperf/
    Report bugs to:     https://github.com/esnet/iperf
    iperf3: parameter error - must either be a client (-c) or server (-s)  <<<< Error given by iperf3 command
    rajkumar:~/automation$

Solution

You are confusing stderr (standard error) with stdout (standard output).

This will work:

iperf3 2>&1 | head -5

The 2>&1 redirects stderr to stdout.

Answered By – JuanR

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published