Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a text file with color

Tags:

bash

I'm trying to write a text file with two colors depending on the output. I using the echo -e command as I would when printing with colors in the console, like this:

RETURNED=$?
if [ $RETURNED == 0 ]
   then
      echo -e "\e[1;32mffmpeg -t $DURACION -f x11grab -s $RESOLUCION -r ${FPS[j]} -b:v $BR -i :0.0 -y $NOMBRE\e[0m" >> file.txt

fi

The idea would be: If the command worked, then write a green line, else use red. However I'm not getting any colored line in the text file.

like image 987
yhabib Avatar asked Mar 13 '14 13:03

yhabib


People also ask

Can TXT files have color?

You can't. Plain text is just that. There is no formatting in a plain text file that lets you specify color/font/size. However, if you are displaying the text in a Bash shell or have configured your windows command console correctly, you could use ANSI Escape Codes to format the text.

How do I change the color of a text file?

You can change the color of text in your Word document. Select the text that you want to change. On the Home tab, in the Font group, choose the arrow next to Font Color, and then select a color.


2 Answers

Have you tried less -R file.txt? That should show you the colour (works for me at least).

If you want colour coding which is supported by non-shell applications your best bet is probably to output HTML, for example:

printf '<code style="color: %s;">%s</code>' "green" "ffmpeg -t $DURACION -f x11grab -s $RESOLUCION -r ${FPS[j]} -b:v $BR -i :0.0 -y $NOMBRE" >> file.html
like image 71
l0b0 Avatar answered Oct 15 '22 17:10

l0b0


Use printf instead of echo -e:

printf portably supports interpreting \-based escape sequences, whereas echo -e isn't supported on all platforms, notably not on macOS.

printf "\e[1;32mffmpeg -t $DURACION -f x11grab -s $RESOLUCION -r ${FPS[j]}\
-b:v $BR -i :0.0 -y $NOMBRE\e[0m\n" >> file.txt

Note the trailing \n to print a newline after the string, because printf - unlike echo - doesn't automatically add one.

like image 44
mklement0 Avatar answered Oct 15 '22 17:10

mklement0