Getting started with bash scripting

Guides By 5 years ago

From my last post you would know that I have been working with OpenCV. Today’s blog post is going to be continue on that theme by showing how a simple bash script can help when testing OpenCV applications. One thing to remember about bash scripting that, like Python, whitespace matters.

Lets start by looking at the following script.

#!/bin/bash

tPattern="anz|commbank"
qPattern="blue|comm"

train=$(find ./train | grep $tPattern)
query=$(find ./query | grep $qPattern)

for i in $train; do
    for j in $query; do
        ./bin/match-shape $i $j
        echo $i $j
    done
done

It may look a little cryptic however this script just runs a program passing it two images from two different directories and loops over all of the combinations.

The first line starts with a ‘#!’ or shebang. Usually the ‘#’ represents a single line comment but when used in combination with the ‘!’ character it has special meaning. A shebang used as the first two characters in a file in this manner specifies which program to run when interpreting the script. In this case the program to run is the bash shell.

The following two lines show variable assignment. We will come back to these in a moment for now just take note that a backslash in double quotes is used to escape characters.

Now we are getting to the interesting part of the script. As you can probably recognise from the previous couple of lines the next statements also indicate variable assignment. On the right side of the assignment expression there is a command substitution denoted by the ‘$(COMMAND)’.

A command substitution does exactly that, substitues the results of a command into something else, in this case a variable. In the middle of the commands is the pipe operator , ‘|’ which takes the output of one command and feeds it into the input of another command.

On the left of the pipe is the find command used to traverse a directory structure and on the right, grep which is used to search for text. Notice the ‘$’ in front of the variable tPattern, this indicates that a variable is being referenced rather than assigned.

Looking at the line beginning with ‘train’ the command inside the ‘$()’ finds all the files/directories inside the directory and then pipes the list to the grep command that then returns files that match ‘$tPattern’. For grep commands when a ‘|’ appears in a double quoted block it represents or. In the example, tPattern is assigned “anz|commbank”  indicating anything that matches “anz” or “commbank” will be returned.

The final part of the script shows how to use a nested for loop construct and makes use of the ‘echo’ command, which just prints the names of the current files to the screen.

Remember to make your script executable before trying to run it.

 
chmod u+x your-script     # make your-script executable for the user
./your-script             # run your-script

That concludes today’s blog post. Hope you found it useful.