Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How display color message from bash script?

Tags:

bash

colors

I found this example:

echo -e "This is red->\e[00;31mRED\e[00m"

It works if execute direct, from command line, bu if create file like:

#! /usr/bin/sh
echo -e "This is red->\e[00;31mRED\e[00m"

Doesn't work. How to fix? Or may be possible output in bold? Please don't use Lua it doesn't installed.

like image 994
user710818 Avatar asked Feb 23 '23 06:02

user710818


2 Answers

Edit This might be your problem (likely):

#!/bin/bash
echo -e "This is red->\e[00;31mRED\e[00m"

The reason is that sh doesn't have a builtin echo command, that supports escapes.

Alternatively you might invoke your script like

bash ./myscript.sh

Backgrounders

ANSI escape sequences are interpreted by the terminal.

If you run in a pipe/with IO redirected, ouput won't be to a terminal, hence the escapes don't get interpreted.

Hints:

  • see ansifilter for a tool that can filter ANSI escape sequences (and optionally translate to HTML and others)
  • use GNU less, e.g. to get ANSI escapes working in a pager:

    grep something --colour=always files.* | less -R
    

Or simply, as I do

# also prevent wrapping long lines
alias less='less -SR'

like image 84
sehe Avatar answered Feb 24 '23 21:02

sehe


Use an echo program, not an echo built-in command:

#!/bin/sh
MYECHO="`which echo`"
if <test-whether-MYECHO-empty-and-act-accordingly> ...
...
$MYCHO -e "This is red->\e[00;31mRED\e[00m"
like image 35
pell Avatar answered Feb 24 '23 19:02

pell