3

I'm running grep inside a bash script. If I run the grep command directly, I see colored output of the file name and search string:

grep -i username /tmp/sess_*

If I put that command in a bash script, it works, but the colors are lost. How can I preserve the colored output?

5

You could add --color=always to your grep.

Relevant section from my local manpage:

  --color[=WHEN], --colour[=WHEN]
          Surround  the  matched  (non-empty)  strings,  matching   lines,
          context  lines,  file  names,  line  numbers,  byte offsets, and
          separators (for fields and groups of context lines) with  escape
          sequences  to display them in color on the terminal.  The colors
          are  defined  by  the  environment  variable  GREP_COLORS.   The
          deprecated  environment  variable GREP_COLOR is still supported,
          but its setting does not have priority.  WHEN is never,  always,
          or auto.

As this question on SO suggests, probably you have an alias for grep that maps it to grep --color=auto in your .bashrc and that isn't read by the script, and so isn't applied within the script.

  • Awesome! This worked perfectly. – Sonny Jan 8 '16 at 15:13

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.