How to change the output color of echo in Linux

后端 未结 29 4014
刺人心
刺人心 2020-11-22 04:28

I am trying to print a text in the terminal using echo command.

I want to print the text in a red color. How can I do that?

29条回答
  •  温柔的废话
    2020-11-22 05:05

    We can use 24 Bits RGB true colors for both text and background!

     ESC[38;2;⟨r⟩;⟨g⟩;⟨b⟩m  /*Foreground color*/
     ESC[48;2;⟨r⟩;⟨g⟩;⟨b⟩m  /*Background color*/
    

    Example red text and closing tag:

     echo -e "\e[38;2;255;0;0mHello world\e[0m"
    

    Generator:

    text.addEventListener("input",update)
    back.addEventListener("input",update)
    
    function update(){
      let a = text.value.substr(1).match(/.{1,2}/g)
      let b = back.value.substr(1).match(/.{1,2}/g)
      out1.textContent = "echo -e \"\\" + `033[38;2;${parseInt(a[0],16)};${parseInt(a[1],16)};${parseInt(a[2],16)}mHello\"`
      out2.textContent = "echo -e \"\\" + `033[48;2;${parseInt(b[0],16)};${parseInt(b[1],16)};${parseInt(b[2],16)}mWorld!\"`
    }
    div {padding:1rem;font-size:larger}
    TEXT COLOR: 
    
    BACK COLOR:

    24-bit: As "true color" graphic cards with 16 to 24 bits of color became common, Xterm,KDE's Konsole, as well as all libvte based terminals (including GNOME Terminal) support 24-bit foreground and background color setting https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit

    Is it safe to use in my scripts?

    Yes! 8 and 16 bits terminals will just display as fallback a color on the range of the available palette, keeping the best contrast, no breakages!


    Also, nobody noticed the usefulness of the ANSI code 7 reversed video.

    It stay readable on any terminal schemes colors, black or white backgrounds, or other fancies palettes, by swapping foreground and background colors.

    Example, for a red background that works everywhere:

    echo -e "\033[31;7mHello world\e[0m";
    

    This is how it looks when changing the terminal built-in schemes:

    This is the loop script used for the gif.

    for i in {30..49};do echo -e "\033[$i;7mReversed color code $i\e[0m Hello world!";done
    

    See https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

提交回复
热议问题