Here is a simple wrapper for grep for searching through a Git repository. For some reason, the colors are gone when grep is called though a bash script. How do I fix it?

enter image description here

I was using this command

grep $1 . -R --exclude-dir=.git --line-number

When you run grep in a terminal it shows colours because of this default alias in your ~/.bashrc

alias grep='grep --color=auto'

~/.bashrc is only sourced by interactive shells. When you run a script, it runs in a non-interactive shell, so the alias is not available.

To preserve the colouring, add the --color=auto flag to the grep command inside the script:

grep $1 . -R --exclude-dir=.git --line-number --color=auto
  • 4
    Also note that with --color=auto, colors will be lost if you redirect the output (a good thing). – user423626 Sep 4 '16 at 12:49
  • 3
    @BharadwajRaju Except when you pipe it to something like less, in which case you have to specify --color=always and use less -R to display the coloured output inside less. – Bakuriu Sep 4 '16 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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