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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 20 down vote accepted

You could use a function in bash like this:

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

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

share|improve this answer
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

Your Answer


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.