MoreBash:Scripts - Introduction

From Juneday education
Jump to: navigation, search

Introduction

In the lecture for this chapter, we'll introduce the concept of scripting in bash, creating so called shell scripts.

A shell script is a simple source code file with bash commands and often also functions.

It's worth noting that anything you can do in a shell script, you can do interactively, one instruction at the time in the command line interactive bash shell.

Tasks that require many steps, and are tasks which you perform often (more than once) are often suitable for making scripts. Rather than performing the same bash commands over and over, you save them in a script which you can run as many times you like.

Another benefit with scripts, is that you can give arguments and options to them, so that they behave differently each time you run them, based on the arguments and options. In this way, a script works pretty much like any other command or program you run in bash.

In the first lecture (of two), we look at a simple script for printing some statistics about a directory. We will also guide you through the mostly used control flow constructs (such as if, for, while..). In the second lecture we look at scraping data from a restaurant to figure out today's lunch offer. This lecture is a little more advanced and serves mainly as a teaser to show how to mangle text which we get from the web. We discover that this is probably something we'd like to do every day. So, the command lines for fetching the data about today's lunch is converted to a script.

The script extracts the relevant lines of text from a web page using w3m. The text is then parsed (mangled) to find the relevant lines of text with "today's" lunch offer, using a lot of different text filter commands glued together with pipes. You don't have to understand all the steps of this lecture in order to see what you can do with a few lines of code in a bash script.

The script is also made generic in that it calculates today's week day using date if no argument is given.

You will see how to use arguments to scripts, check the number of arguments, and how to pipe together some text filters to extract the exact lines of text you are looking for.

Please see this as an inspiration rather than something you must immediately understand and learn.

Writing scripts requires a bit of theory abd a whole lot of practice so, as always, we really recommend doing the exercises as found in the next chapter MoreBash:Exercises - Scripts - Introduction.


Videos

Lecture 1

Lecture 2

Links

External links (further reading)

Where to go next

Next page contains exercises for this topic.

« PreviousBook TOCNext »