Basic Linux Shell Scripting Concepts

Batch Files vs Scripts

A batch file is a type of script that used only operating system commands and executes those commands in sequence. The commands are executed as entered and the author generally has little control over the flow of the script. Scripts must be translated from the language they are written in to machine language for execution. This is called interpretation.

The Role of the Shell

The shell you are running plays an important part in your ability to write scripts. The shell you use IS your scripting language. Shells natively contain the elements of scripting languages such as conditional logic and looping. Another key element of shells is its ability to evaluate expressions (i.e. name = “Frank”). Shells such as BASH have good expression evaluation, while shells such as the C Shell (csh) have the capability of the C language, which is much more flexible and powerful, albeit with more complex syntax. Generally the shell only provides the ability to evaluate expressions and provide logic. All actual operations are accomplished by calling external commands. For example, if you wanted to write a script to log an error, you would use the [cat] command from within your script to append a line of text to a file which has been designated your error log. In order for a script to run on a computer you must ensure you have the utilities required by your script installed.

Creating a Simple Script

To create a simple Linux shell script create a new file in your root folder called [myFirstScript]. Using vi, enter the following text in the file.


#!/bin/bash

echo My First Script

ls > output.dir

The first line is known as a shebang (shell bang (#)). This line tells Linux to use the bash shell to execute this script. The second line will output some text to the console, and the third line uses shell redirection to store the results of an ls command in a file.

Save the file and then at the shell prompt execute the following.

[chmod u+x myFirstScript]

This will turn on the execute bit. Unlike Windows where the extension of the file determines the files ability to execute, Linux uses the execute bit. Next run the script by typing.

[./myFirstScript]

In Linux the path is very important, this will be discussed in more detail later. For now, you must explicitly state that we want to execute the file located in this directory.