Grep – How to Create a Grep Alias with Line Numbers Unless in a Pipeline

aliasgrepio-redirection

I want to create a bash alias for grep that adds line numbers:

alias grep='grep -n'

But that, of course, adds line numbers to pipelines as well. Most of the time (and no exceptions come to mind) I don't want line numbers within a pipeline (at least internally, probably OK if it's last), and I don't really want to add a sed/awk/cut to the pipeline just to take them out.

Perhaps my requirements could be simplified to "only add line numbers if grep is the only command on the line." Is there any way to do this without a particularly ugly alias?

Best Answer

You could use a function in bash (or any POSIX shell) like this:

grep() { 
    if [ -t 1 ] && [ -t 0 ]; then 
        command grep -n "$@"
    else 
        command grep "$@"
    fi
}

The [ -t 1 ] part uses the [ command (also known as test) to check if stdout is associated with a tty.

The [ -t 0 ] checks standard input, as well, since you specified to only add line numbers if grep is the only command in the pipeline.