Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 14 down vote accepted

You could use a function in bash like this:

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

The -t 1 part test for stdout to be a tty or not.

share|improve this answer
1  
And make the test [[ -t 0 && -t 1 ]] if you only want line numbers if both standard input and standard output are connected to a terminal. –  Gilles Nov 28 '11 at 17:20
    
Exactly what I needed, thanks! –  Kevin Nov 28 '11 at 18:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.