3

I am setting up a zsh shell environment and I wanted to try writing a simple function for my own learning purposes:

# ~/.zsh-extensions/conda_which

# get version in conda env
function conda_which {
    # this comes from Flament's answer below
    readonly env=${1:?"The environment must be specified."}
    readonly pkg=${2:?"The package must be specified."}

    conda list -n $env | grep $pkg
}

and in my .zshrc

# ~/.zshrc

# this comes from Terbeck's answer below
fpath=(~/.zsh-extensions/ $fpath)

# this comes from _conda file recommendation for conda autocompletion
fpath+=~/.zsh-extensions/conda-zsh-completion

# this comes from Terbeck's answer below
autoload -U $fpath[1]/*(.:t)

So now I can do:

$ conda_which test_env numpy
numpy                     1.23.5          py310h5d7c261_0    conda-forge

instead of

$ conda list -n test_env | grep numpy

because I often forget if it is env list or list env and this is just a toy example.

The issue I am facing is that the output of conda_which losses grep's color highlighting numpy. How do I maintain this?

citations:

1 Answer 1

4

Grep doesn't have color by default. Instead, the colors can be enabled by the user. Many modern Linux systems ship with grep aliased to grep --color. For example, on my Arch:

$ type grep
grep is aliased to `grep --color'

Now, GNU grep is clever enough to detect when its output is being piped and will disable color unless you use another option that tells it to always print colored output. From man grep:

      --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.  WHEN is
              never, always, or auto.

The info page for grep gives a bit more detail:

WHEN is ‘always’ to use colors, ‘never’ to not use colors, or ‘auto’ to use colors if standard output is associated with a terminal device and the TERM environment variable’s value suggests that the terminal supports colors. Plain --color is treated like --color=auto; if no --color option is given, the default is --color=never.

What all this means is that if you run grep or grep --color and its output is being piped to something else, then grep won't output color codes. To force it to, you need to use --col9or=always. So, in your function, try something like this:

conda list -n "$env" | grep --color=always "$pkg"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.