Search code examples
bashterminalgrepnpm-link

Keep npm linked folder color in grep on terminal


I have a folder in node_modules which is linked to another project (using npm link my-plugin). Let's call it my-plugin.

When I run ls node_modules I get a list with all folders which contains my-plugin of course. The my-plugin folder has a different color (to notice me that it linked).

enter image description here

Now, I have a lot of folders in node_modules and I want to get only the certain folder so I'm using grep. Something like this:

ls node_modules | grep my-plugin

The problem is that grep painting the expression so I'm missing the linked color of my-plugin.

enter image description here

The problem is that sometimes I run my app with the link and sometimes with the original plugin so I need to know if it linked now or not.

I hope it's clear. If not, let me know.


Solution

  • The colouring of the output of ls is determined by the LS_COLORS environment variable, which is often set in .bashrc by evaluating the output of dircolors -b, or using a custom file, as in dircolors -b "$HOME/.dircolors". Mine contains, for example,

    # Symbolic link
    LINK 35
    

    which renders links as purple.

    Grep, on the other hand, colourizes its output as determined by the GREP_COLORS environment variable. It is a string of colon separated capabilities; the default is for my grep is

    ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36
    

    where the important part is ms=01;31: it sets

    SGR substring for matching non-empty text in a selected line.

    where "SGR" is "Select Graphic Rendition"; 01;31 sets the pattern matched by grep to bold red over the default background.

    So, no matter what LS_COLORS sets your linked directories to, grep will always use its own colours for matches as it has no way of knowing what the text it is looking at means.

    A workaround could be to filter types with find:

    find node-modules -type l -name 'my-plugin'
    

    will return matches only if they are links.