Thursday, January 24, 2019

How to get coloured output from 'find'

When I need to get coloured output from shell scripts (e.g. in error messages) I am using the oldstyle escape sequences.

Example:

printf "\e[31mERROR - some error description\e[0m\n"
which will result in
ERROR - some error description
\e[31m is basically ESCAPE and a colour code (31 for red, see ANSI escape codes) for colour terminals. \e[0m ends the colouring.

I wanted to use the colour escape sequences in the printf of find.

This does not work when using \e and an error is thrown:

find . -printf "\e[31mSome Output\n" -quit
find: warning: unrecognized escape `\e'
\e[31mSome Output
The solution is to replace \e by its octal representation \033 (see e.g. ASCII table).
find . -printf "\033[31mSome Output\n" -quit
Some Output

Of course the find command in the example is not really useful (it quits right away) and it is only used to showcase the issue. Here is a more useful invocation:

find empty and non-empty sub directories whereas non-empty should be coloured.

# Create example directories
mkdir -p tmp/a tmp/b tmp/c; touch tmp/b/foo

# Find
find tmp -type d \( -empty -printf "%-10p empty\n" \) -o \
\( ! -empty -printf "\033[31m%-10p not empty\033[0m\n" \)
tmp        not empty
tmp/a      empty
tmp/b      not empty
tmp/c      empty
i.e. I can distuingish in find between different cases and apply different colours according to my needs.