Search code examples
bashcentos7netstat

Loop creating infinite grep process


I have coded a bash script to not show certain port when someone uses netstat. I have placed it in .bashrc file.

function test(){
    if [ ! -n "$1" ]; then
       netstat | grep -v 1111;
    else
       netstat "$1" | grep -v 1111;
    fi
}
alias netstat='test'

When executed, sometimes when executing netstat | grep 1111 (not always and it is not possible to specify in which situations) it creates an infinite number of grep processes.

The expected result is to return netstat output without the filtered port.


Solution

  • There's no need for an alias, and you can use the command command to differentiate between your function netstat and the "real" command netstat.

    netstat () {
        if [ -z "$1" ]; then
            command netstat
        else
            command netstat "$1"
        fi | grep -v 1111
    }
    

    If your actual intention is to determine if there is an argument, rather than simply a non-empty argument (i.e., differentiate between netstat and netstat ""), you can reduce this (in bash) to

    netstat () {
        command netstat "${@:1:1}" | grep -v 1111
    }
    

    The parameter expansion "disappears" if $# really is 0.