Ubuntu – Colors missing when calling grep through script

bashcommand linegrepscripts

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

Best Answer

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
Related Question