6

Is there a way to add a prefix to lines received (and filtered) via awk - yes I know that's possible so far - and then conditionally (e.g. based on the existence of the $PS1 variable of the surrounding Bash script or [ -t 1 ]) color it using ANSI escape sequences?

I know how to add a prefix using the ^ anchor and about two or three other ways and I know how to use escape sequences in Bash echo and printf.

How - if at all - can I color the output produced by awk as outlined, based on a condition that can be evaluated inside an inline awk script?

NB: I have mawk or gawk at my disposal, mawk is default.

1
  • It seems that scripts don't have PS1. Jun 5, 2014 at 3:12

2 Answers 2

7
if [ -t 1 ]; then
  eval "$(printf 'COLOR_ON="\033[31m" COLOR_OFF="\033[m"')"
else
  COLOR_ON= COLOR_OFF=
fi
export COLOR_ON COLOR_OFF
awk '{print ENVIRON["COLOR_ON"] "prefix: " ENVIRON["COLOR_OFF"] $0}'

Or:

[ ! -t 1 ]
awk -v color="$?" '{
   print((color ? "\033[31m" : "") "prefix: " (color ? "\033[m" : "") $0)}'
0

You can check for a terminal this way:

> echo foo | awk '{if (system("tty >/dev/null 2>&1")) print "true"; else print "false";}'
true
8
  • Thanks, that solves the first part. Alas, the awk output does not seem to interpret escape sequences. So to output for example a green true, the escape sequence gets blurted out verbatim ("\033[1;32mtrue\033[0m"), where the outer quoting uses single quotes as in your example. Unfortunately echo takes no input from stdin, so appending |echo -e doesn't work (neither with /bin/echo). Jun 5, 2014 at 3:33
  • while IFS= read -r line; do echo -e "$line"; done ? Jun 5, 2014 at 3:42
  • On another note, your example always gives me false as output and the not a tty actually ends up on the terminal. The while read might do the job, cat - also does I just found out. Running tty standalone in the same terminal I run your command in, yields /dev/pts/7, so this method may have some dependencies. Did you use gawk or mawk? Jun 5, 2014 at 3:42
  • 3
    tty &>/dev/null is not POSIX. Well it is, but it means run tty in background and truncate /dev/null (same as tty & > /dev/null). That's bash syntax, you should not use it in system() which spawns the system's sh. Use tty > /dev/null 2>&1. Jun 5, 2014 at 5:43
  • 2
    Note that tty checks if there's a controlling terminal, not if stdout is a terminal (well in this case, tty's stdout is /dev/null anyway). Jun 5, 2014 at 9:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .