Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to tail -f with colored lines

Tags:

linux

bash

perl

I tried to create a script from this suggestion like this :

#!/bin/bash

if [ $# -eq 0 ]; then
        tail -f /var/log/mylog.log
fi


if [ $# -eq 1 ]; then
        tail -f /var/log/mylog.log | perl -pe 's/.*$1.*/\e[1;31m$&\e[0m/g'
fi

It shows black tail of the file when I pass no arguments to the script, but every line is red when I pass an argument. I would like it to color only lines which contain the word passed to the script.

For example, this would color lines containing word "info" :

./color_lines.sh info

How to change the script to work with one argument?

like image 808
BЈовић Avatar asked Jan 14 '23 05:01

BЈовић


1 Answers

Do not quote the argument variable:

tail -f input | perl -pe 's/.*'$1'.*/\e[1;31m$&\e[0m/g'

You can also use grep for this:

tail -f input | grep -e $1 -e ''  --color=always

and to color the whole line with grep:

tail -f input | grep -e ".*$1.*" -e ''  --color=always
like image 112
perreal Avatar answered Jan 16 '23 20:01

perreal