bash command preserve color when piping [duplicate] bash command preserve color when piping [duplicate] bash bash

bash command preserve color when piping [duplicate]


Here's a script snippet using the colorized output of ls as an example (on Mac OS X 10.6).

# no colored ls output if stdout is a pipe (and not a tty)ls -G /ls -G / | catscript -q /dev/null ls -G / | tr -d '\r' | cat# write output of script command to a variablevar="$(script -q /dev/null ls -G / | tr -d '\r' | cat)"echo "$var"


Most commands that do print out those color codes explicitly check if stdout/stderr is a tty (using the isatty function).

If you want to preserve the color codes, you can run it within a terminal emulator like screen or the direct logger script, saving the output to a file.