RSS Feed Share on Twitter

All Shell Scripting Tips

15 May 2015

Nifty use of grep in a loop

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 script

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



You can buy the content of this tutorial as a PDF to download to all of your devices!


You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!