2

I'm piping some Unix commands with my own scripts. The problem is that in my scripts, I'm using colors. Like for example:

yellow=`tput setaf 3`
reset=`tput sgr0`

function Warning()
{
    echo "${yellow}$*${reset}"
}

I have a command that prints the path of some directories, using Warning "Compress $directory".

I want to pipe it into the find command.

I'm using:

./compress.sh | grep Push | awk '{print $2}' | while read directory; do find $directory | wc -l; done;

However, I get this error:

find: ‘/some_directory\033(B\033[m’: No such file or directory 0

It seems that either awk puts some invisible characters to the end of its print, or the color messes up with piping.

Why do I get this error? What should I do?

1 Answer 1

3

Terminal colors work via escape sequences. ${yellow} is really \033[0;33m (or \e[0;33m) and ${reset} is \033[0m. You can try it out with echo -e '\e[0;33m yellow \e[0m' (list of the basic color codes).

\033 means the char with the octal number 033, that's Escape in ASCII and Unicode. \e is another way to mean Escape. The [ marks the start and the m marks the end of the code.

Most programs can't interpret color codes, so you have to disable them if you are piping. You can detect if your program is running in a pipe, when [[ -t 1 ]] is true, you are writing to a terminal, if it is false you are writing elsewhere, probably a pipe.

This will only output colors when you are printing to a terminal:

yellow=''
reset=''
if [[ -t 1 ]]; then
    yellow=`tput setaf 3`
    reset=`tput sgr0`
fi

function Warning()
{
    echo "${yellow}$*${reset}"
}
1
  • That is the proper approach. Sep 23, 2022 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.