The Shell Scripting Tutorial


Nifty use of grep in a loop

A handy tip using the --color feature of GNU's grep tool

15 May 2015

Grep is a widely known and used tool, but here is a use that you may not have considered before.

GNU's grep, as used in Linux systems, and also available on some Unix systems (it may be installed as ggrep), has some additional features, one of which is --color, which can be used to highlight the matching section of the line.

For example, here it's showing where the word "file" is found in a file.

grep output

That is handy, but it's not the neat bit. Here it comes: You can use this to highlight a given item in a list.

A loop might configure and build some software, then package it up, distribute it and install it on client systems. It's quite a time-consuming process, and you want to easily be able to check on its progress. By using grep --color, we can automatically highlight the current step in the process.

grep output

Now, each step (configure, make, package, distribute, install) is highlighted, simply by using grep:
echo "${STEPS}" | grep --color ${ACTION}
This echoes out the full list of steps (of course, it's only one line), and then uses grep to match the individual step (the line is guaranteed to match, so the line always gets displayed, which makes the grep seem rather useless. The only thing we're gaining, is that GNU grep also does this colour highlighting, causing the current action to be highlighted in red text.

Note: The other text, "Running ${ACTION}" is just a placeholder to show you where some other script output might go.

Download grep-loops.sh script
#!/bin/bash

STEPS="configure make package distribute install"
for ACTION in $STEPS
do
  echo "*****************************************"
  printf "*** Running action: %-15s (" *${ACTION}*
  echo "${STEPS})" | grep --color ${ACTION}
  echo "Running ${ACTION} ... Running ${ACTION} ... "
  echo "Running ${ACTION} ... Running ${ACTION}"
  sleep 1
  echo
done


My Paperbacks and eBooks

My Shell Scripting books, available in Paperback and eBook formats. This tutorial is more of a general introduction to Shell Scripting, the longer Shell Scripting: Expert Recipes for Linux, Bash and more book covers every aspect of Bash in detail.

Shell Scripting Tutorial

Shell Scripting Tutorial
is this tutorial, in 88-page Paperback and eBook formats. Convenient to read on the go, and in paperback format good to keep by your desk as an ever-present companion.

Also available in PDF form from Gumroad:Get this tutorial as a PDF
Shell Scripting: Expert Recipes for Linux, Bash and more

Shell Scripting: Expert Recipes for Linux, Bash and more
is my 564-page book on Shell Scripting. The first half covers all of the features of the shell in every detail; the second half has real-world shell scripts, organised by topic, along with detailed discussion of each script.