3.0 Bash Scripting

Topics

  • bash and bash completion

  • streams

  • pipes

  • redirects

  • find and grep

  • Manuals

  • environment variables

  • alias

Reading List

Chapter

  • 2 create or update the manual page index caches|

Commands

Command

Action

grep

print lines matching a pattern

find

search for files in a directory hierarchy

cat

concatenate files and print on the standard output

bash

reloads the bash shell

echo

display a line of text

env

run and see programs in a modified environment

man

an interface to the online reference manuals

mandb

create or update the manual page index caches

3.0.1 Bash scripts: Shebang

When starting a file with execute permissions the Operating System has to know what kind of file it is. Windows desktop uses the file extention, the Linux commandline shells use the first line of a file. This is called a hashbang (#!) or a shebang, followed by the path to a interpreter, like Bash or Python.

#!/usr/bin/bash

Let’s try to make a file named hello.sh with executable permissions set for the user, and a shebang on top. Use the echo "Hello World" as second line.

Now try to execute the file.

Next we are adapting the file as follows:

#!/usr/bin/bash

echo $1

Now start your program with something extra: ./hello.sh "Hello Greater"

What does the $1 do in the code above? Try again with ./hello.sh Hello Greater

Did we find a $2 in there?

3.0.2 Bash scripts: Conditionals

If statements allow us to make decisions in our Bash scripts. They allow us to decide whether or not to run a piece of code based upon conditions.

example1.sh

#!/usr/bin/bash

if [[ "greater" == "GREATER" ]]
then
    echo "This is not the same"
fi

example2.sh

#!/usr/bin/bash

if [[ "greater" == "greater" ]]
then
    echo "This is the same"
fi

You can use the following operators:

operator

description

! EXPRESSION

The EXPRESSION is false.

-n STRING

The length of STRING is greater than zero.

-z STRING

The lengh of STRING is zero (ie it is empty).

STRING1 == STRING2

STRING1 is equal to STRING2

STRING1 != STRING2

STRING1 is not equal to STRING2

INTEGER1 -eq INTEGER2

INTEGER1 is numerically equal to INTEGER2

INTEGER1 -gt INTEGER2

INTEGER1 is numerically greater than INTEGER2

INTEGER1 -lt INTEGER2

INTEGER1 is numerically less than INTEGER2

INTEGER1 -le INTEGER2

INTEGER1 is numerically less than or equal to INTEGER2

INTEGER1 -ge INTEGER2

INTEGER1 is numerically greater than or equal to INTEGER2

3.0.3 Bash scripting: Loops

Sometimes we want to repeat one or a few lines of code until a certain condition is met.

We can use for and while in those cases. There is a slight difference, can you spot them in the examples?

for i in {1..10}
do
    echo $i
done
i=0
while [[ $i -le 10 ]]
do
    echo $i
    i=$(($i+1))
done