Linux less with color

Can less retain colored output?

Can I get less not to monochrome its output? E.g., the output from git diff is colored, but git diff | less is not.

10 Answers 10

git diff --color=always | less -r 

—color=always is there to tell git to output color codes even if the output is a pipe (not a tty). And -r is there to tell less to interpret those color codes and other escape sequences. Use -R for ANSI color codes only.

@ripper234. With recent gits, git config color.ui true should be enough to obtain colored output, and to automatically run a pager for long outputs.

In parallel to this Q/A, watch —color ‘git diff —cached —color=always’ and its friends can bring you some additional awesomeness.

Isn’t using less -R better (or export LESS=R in /etc/profile )? Why would you allow it to display anything but ANSI «color» escape sequences? Also, the man page says Warning: when the -r option is used, less cannot keep track of the actual appearance of the screen (since this depends on how the screen responds to each type of control character). Thus, various display problems may result, such as long lines being split in the wrong place.

And if you forgot to specify -r option, you can just type «-r» at the less prompt. This of course works with most or all less options (i.e., -i to turn on ignorecase).

grep —color=always works the same way. This is not part of this question or answer, but I got here from googling about that question so there it is.

Another option would be to enable colors and use ‘less -r’ as your pager.

git config --global color.ui true git config --global core.pager 'less -r' 
[color] ui = true [core] pager = less -r 

For more information see the Pro Git book.

Possible values for color.ui can be found in the man page of git-config. The output of man git-config | grep «color.ui$» -A8 is

color.ui This variable determines the default value for variables such as color.diff and color.grep that control the use of color per command family. Its scope will expand as more commands learn configuration to set a default for the --color option. Set it to false or never if you prefer Git commands not to use color unless enabled explicitly with some other configuration or the --color option. Set it to always if you want all output not intended for machine consumption to use color, to true or auto (this is the default since Git 1.8.4) if you want such output to use color when written to the terminal. 

Using Git 2.11, I found that color.ui true did not work with a pager, but color.ui always did. This may have changed since the answer was posted.

Читайте также:  Linux file system usr share

This option (to enable colors and use ‘less -r’ as your pager by default) with color.ui true do work for comands like git -p diff and git -p status (where -p means pipe all output into $PAGER, by default it’s less ) even for rather old versions of git (for example, Git 1.7.1). But you still need color.ui always (which tells git to output color codes «even if the output is a pipe (not a tty)») to get colored output when you directly specify git status | less -r or git diff | less -r . When you specify output redirection explicitly, you won’t see the output after quit from pager.

git status | less and git -p status seem to behave exactly the same for me when color.ui always is set — but since the former both requires a discouraged configuration option and is longer, I’ll simply go with the latter ^^

Use -r ( —raw-control-chars ) option to less, or also -R (only ANSI escape sequences).

I have an alias for this in ~/.bashrc

@ripper234: I vaguely remember there could be cases when using -r when not needed can lead to visualization problem.

Uh, you don’t have to alias less to anything, just set the $LESS environment variable to the set of flags you always want to provide to less , e.g. export LESS=’-MRq -z-2 -j2’

In case anyone is interested in paging a json with jq and less it can be achieved using:

Also tree has an option to force colors on:

I know this is old and many have already provided the right answer but I would like to add that it is always better to use less -R and not less -r if you only need ANSI colors as -r may cause problems in displaying the characters.

 -r or --raw-control-chars Causes "raw" control characters to be displayed. The default is to display control characters using the caret notation; for example, a control-A (octal 001) is displayed as "^A". Warn‐ ing: when the -r option is used, less cannot keep track of the actual appearance of the screen (since this depends on how the screen responds to each type of control character). Thus, var‐ ious display problems may result, such as long lines being split in the wrong place. -R or --RAW-CONTROL-CHARS Like -r, but only ANSI "color" escape sequences are output in "raw" form. Unlike -r, the screen appearance is maintained correctly in most cases. ANSI "color" escape sequences are sequences of the form: ESC [ . m 

Источник

Re: less в цвете

А вот я хз как ))) Просто интересно было — а нельзя ли сделать чтобы less принимая от ls данные сохранял цвета. Ну или аналоги какие-то less.

Re: less в цвете

(72 замени в соответствии с имеющейся версией vim’а)

Re: less в цвете

Re: less в цвете

> чтобы less принимая от ls данные сохранял цвета

То, что я предложил, такого не даст 🙁

Re: less в цвете

Re: less в цвете

Re: less в цвете

А еще можно файлы раскрашивать через внешний колорайзер.

Читайте также:  Linux more less most

Вставить его точно так же, как и распаковщики на определенный тип файла.

Re: less в цвете

1) При просмотре вывода программ, способных окрашивать вывод и обнаруживать пайпы, использовать с этими программами ключи наподобие —force-colour (grep —colour=always, ls —color и т.п.)

2) Для подсветки синтаксиса текстовых файлов и вывода архиваторов надо править /usr/bin/lesspipe.sh.

3) Не знаю про другие дистрибутивы, но в Генту с less идёт файл /usr/bin/code2color, для подсветки сиинтаксиса с использованием HTML. Можно задействовать его.

Re: less в цвете

alias ls=’ls —color’
alias less=’less -NR’

Re: less в цвете

Re: less в цвете

>2) Для подсветки синтаксиса текстовых файлов и вывода архиваторов надо править /usr/bin/lesspipe.sh.

Зачем править lesspipe.sh? ~/.lessfilter же есть? 🙂

Re: less в цвете

У меня нету. И никаких намёков на него в документации.

Поискал ещё в документации. Похоже, code2color — чисто гентушнная добавка. Подсветка синтаксиса включается export LESSCOLOR=yes, заменить code2color чем-то ещё можно через export LESSCOLORIZER=some-other-script.

Re: less в цвете

А глянь в lesspipe.sh, там не вызывается какой-нибудь скрипт/программа из /home или на худой конец из /etc? У меня вдруг подозрение возникло, что это Debian-specific feature, так как документация к lesspipe в дистрибутиве написана специально для Debian.

color2color — это да, наверное в Генте (я точно не знаю). Но никто не запрещает установить и другой колорайзер. Есть, например на питоне написанный — python-pygments (команда pygmentize). Наверное, еще есть какие-нибудь.

Re: less в цвете

> А глянь в lesspipe.sh, там не вызывается какой-нибудь скрипт/программа из /home или на худой конец из /etc?

> У меня вдруг подозрение возникло, что это Debian-specific feature, так как документация к lesspipe в дистрибутиве написана специально для Debian.

Похоже. Ни в ванильном, ни в Gentoo такого нет.

> color2color — это да, наверное в Генте

code2color сделано в Генту, на основе перлового Code2HTML.

Источник

How do I make `less` output colors?

When I run a program (for example grep or ls ) without a pager, its output is colored. However when I run it piping its output to less , no colors are shown. For example, this command outputs colored output:

grep —color=always «search string» * | less -R but I tend to use most nowadays instead of less . ALSO: gnu.org/software/src-highlite is a color highlighter (less works too)

2 Answers 2

There are two problems here:

  • Commands like ls —which auto-detect the colour support— don’t find support from pipes
  • less is set to just display colour codes by default.

Both can be overcome but it’s a bit clunky:

This isn’t ls specific. Many commands that support colour also have an override argument.

A slightly more in-depth answer is that ls is checking whether or not its STDOUT belongs to a real terminal or not. When you pipe things around, the STDOUT is set to the STDIN of the next command.

You can see this at work in the ls source code. It’s using the isatty command (a core POSIX interface) to work out what the situation is:

    Are colours on by default:

 print_with_color = (i == color_always || (i == color_if_tty && isatty (STDOUT_FILENO))); 
if (format == long_format) format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line); //. if (isatty (STDOUT_FILENO)) < format = many_per_line; set_quoting_style (NULL, shell_escape_quoting_style); qmark_funny_chars = true; >else

grep does a very similar thing, unless explicitly overridden, it’ll detect colour support, with isatty :

color_option = isatty (STDOUT_FILENO) && should_colorize (); 

Источник

Читайте также:  Linux get current timezone

NEWS & BLOG

coloured directory listing

Many shell commands can produce coloured output; for example, on most distributions the ls command shows files in colours according to the file type:

ls with colour

We tend to take the colour for granted, and interpret it subconsciously. We only really notice it when it’s missing – but if the output of ls is piped through less , the colours are lost.

Adding Colour After Pipe

There are two switches to less that can help us. By default, less displays control characters as caret-character; for example, control-A would be displayed as ^A . The ‑‑raw‑control‑chars (or -r ) switch suppresses the translation of control characters, and in the example above would send control-A to the screen. This switch allows the escape sequences that control colour to pass unchanged, and thus the coloured output is retained.

But there’s a catch. Some escape sequences will affect the appearance of the screen, and less can’t know about the effect they may have on the display. As a result, less doesn’t know exactly what the display looks like, which may lead to odd behaviour such as lines being split in the wrong place.

The alternative is the ‑‑RAW‑CONTROL‑CHARS (or -R ) switch – yes, it is an upper-case long option. This is similar to the -r switch above, but only the ANSI colour escape sequences are output unprocessed (so a control-A will still be displayed as ^A ). This allows less to have a much better understanding of the display, and should avoid line splitting issues and similar.

But there’s another catch. You may find that the following command does not, in fact, show any colour in the output:

If that’s the case, check how ls is aliased:

$ alias ls alias ls='ls --color=auto'

The – -color=auto will cause ls to output colo(u)r only when stdout is a terminal. That means that ls alone shows colour, but when the output is piped to another command, it is suppressed. That can be helpful – no escape sequences are embedded in files if the output is redirected to a file – but it also means no escape sequences, and thus no colour, when the output is piped to less .

The fix: explicitly tell ls to output colour:

Automating

You can also set the environment variable LESS to hold the switches you want set by default:

That means that every time less is run, it will have the following options set:

  • -R – the RAW_CONTROL_CHARS option discussed above
  • -i – searches within less are case-insensitive
  • -X – don’t clear the screen after using less
  • -j5 – put the result of searches on the fifth line of the screen where possible

With that environment variable set, this will produce a coloured output:

Day To Day Use

I have the following in my ~/.bash_profile :

export LESS==RiXj5 alias ls='ls --color'

That give me colour directory listings when piped through less . On the very odd occasion I might want to write a directory listing to a file or similar, I use

Was This Linux Tip Useful?

Let us know in the comments below.

Источник

Оцените статью
Adblock
detector