Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep loses coloring when run from bash script

Tags:

grep

bash

colors

I wrote a simple bash script because I was using a grep command with the same arguments, repeatedly. I'm running it from ~/bin and it runs just fine.

My problem is: All the coloring is gone when it's run through my bash script. The exact same command put right into the commandline nicely color codes line numbers, filenames, etc.

Here's my bash script

#!/bin/bash # grep php files inside of myfolder, recursively and with line numbers  grep -rn --include="*.php" "$2" /home/me/myfolder/$1 
like image 875
jairbow Avatar asked Mar 03 '12 23:03

jairbow


2 Answers

You've probably defined grep as an alias for grep --color=auto in your .bashrc, but that's not loaded by scripts. Use an explicit grep --color in your script.

like image 58
Fred Foo Avatar answered Sep 22 '22 09:09

Fred Foo


When you run a script, a new shell is spawned to do so. This new environment doesn't have the same settings as your default shell. As to how to get the coloring back, I'm not sure. You might try sourcing your profile at the start of the script:

#!/bin/bash source $HOME/.bash_profile 

or whichever file makes sense on your particular unix flavor (.profile, .bash_rc, .bashrc .bash_profile) to name a few.

like image 33
PlexQ Avatar answered Sep 22 '22 09:09

PlexQ