You are on page 1of 48

Chapter 14: Writing Shell Scripts

The Complete Guide to Linux System Administration

Objectives
Understand how shell scripts operate Collect user input and write to the screen from within a script Control command execution using tests and loops Debug shell scripts Understand other types of programming available on Linux

The Complete Guide to Linux System Administration

Scripting Basics
Shell script
Executable file Contains lines of text as would be entered at command line Executed like any other program Used on every Linux system

The Complete Guide to Linux System Administration

Scripting Basics (continued)


Shell script advantages
Can study what is happening on Linux system by viewing contents of scripts that control various system events Can change way anything on system occurs simply by altering relevant shell script

The Complete Guide to Linux System Administration

Interpreting and Compiling Programs


Two basic types of computer programs:
Interpreted programs Compiled programs

Computer language
Programming language Set of words and syntax rules Can be arranged in predefined ways to cause computer to perform tasks

The Complete Guide to Linux System Administration

Interpreting and Compiling Programs (continued)


Keywords
Words used in computer language

Source code
Human readable computer program written by programmer

Binary file
Executable file Source code converted to numeric code that computers CPU can process
The Complete Guide to Linux System Administration 6

Interpreting and Compiling Programs (continued)


Compiled language
Source code converted to binary file before program run by users

Interpreted language
Source code converted into numeric codes at instant user runs program

Shell script
Interpreted program

The Complete Guide to Linux System Administration

Understanding Programming Concepts


Computer program executed one command at a time Statement
Command within program

Programs define list of statements that are executed once, many times, or not at all depending on what happens at some other point in program

The Complete Guide to Linux System Administration

Understanding Programming Concepts (continued)


Statement block
Group of statements

Nesting
One statement block contains another statement block

The Complete Guide to Linux System Administration

Components of a Shell Script


Three basic rules:
First line must indicate name of shell used to interpret script
#!/bin/bash

File must have execute file permission set File must contain valid commands that interpreter can recognize

The Complete Guide to Linux System Administration

10

Components of a Shell Script (continued)


echo command
Prints text to STDOUT channel Example: echo hello world

Test new script


./testscript

The Complete Guide to Linux System Administration

11

Components of a Shell Script (continued)


Exit code
Numeric code returned by program on exit Variable $? used to reference code at command line or in script Value of 0 indicates no problems Nonzero value usually indicates some type of problem or error

The Complete Guide to Linux System Administration

12

Input and Output


read command
Causes shell to pause for user to enter information at keyboard Entered information assigned to variable provided with read command read THEFILE

Define variable by assigning value to name


MyFile="index.html"

The Complete Guide to Linux System Administration

13

Input and Output (continued)


Make sure scripts test validity of user values Use Linux redirection operators to change flow of information to and from commands Can use any Linux redirection operators Treat shell script as any regular Linux command

The Complete Guide to Linux System Administration

14

Using Variables in Scripts


Shell variable
Variable used in shell script

Initialize variable
Assign initial value

Positional variable
Takes value based on information user includes on command line Indicate using dollar sign and number
$0 first variable on command line
The Complete Guide to Linux System Administration 15

Using Variables in Scripts (continued)


$# variable
Contains number of items on command line used to execute script

The Complete Guide to Linux System Administration

16

Conditional and Looping Structures


Selection statement
Determine which parts of program will execute according to values determined as program executes All lines in shell script not necessarily executed when script is run Most shell scripts include selection statements

The Complete Guide to Linux System Administration

17

Conditional and Looping Structures (continued)

The Complete Guide to Linux System Administration

18

Conditional and Looping Structures (continued)


Selection statement
Tests performed in shell scripts only have two possible outcomes:
True False

test command creates type of selection statement to determine if condition true or false

The Complete Guide to Linux System Administration

19

Using if Statements
if command followed by then command
Lists commands to be executed if test succeeds

fi command
Marks end of if statement

Test succeeds
All commands between then and if executed

Test fails
No commands executed

The Complete Guide to Linux System Administration

20

Using if Statements (continued)


test command
Evaluates parameters provided Returns either:
True, value of 1 False, value of 0

if-then-else statement
If test returns value of true
One set of commands executed

If test returns value of false


Another set of commands executed
The Complete Guide to Linux System Administration 21

Using if Statements (continued)

The Complete Guide to Linux System Administration

22

Using if Statements (continued)

The Complete Guide to Linux System Administration

23

Using if Statements (continued)


else command
Adds block of commands Only executed if test returns value of false

exit command
Stops execution of script immediately Returns exit code provided Avoid using exit within loop

The Complete Guide to Linux System Administration

24

Using if Statements (continued)


Comment
Line within script not processed by shell Helps reader understand purpose of script Begins with hash mark #

elif keyword
Used in place of else when using if-then-else When first command in else block another if-thenelse statement

The Complete Guide to Linux System Administration

25

Using if Statements (continued)


case statement
Specify number of possible values for variable Statement block executed for matching value Only one block executed

The Complete Guide to Linux System Administration

26

Adding Loops to a Script


Loop statement
Used to determine whether statement block executed more than once Parts:
Counting variable List of values List of statements

The Complete Guide to Linux System Administration

27

Adding Loops to a Script (continued)


for loop
Repeats statement block once for each item in list Syntax:
for <counting variable> in <list of items> do <statement block> done

The Complete Guide to Linux System Administration

28

Adding Loops to a Script (continued)


Iteration
Each time through loop

$@ variable
Contains all parameters included on command line when script executed Used as <list of items> in for loop

The Complete Guide to Linux System Administration

29

Adding Loops to a Script (continued)


while loop
Uses test like if-then statement As long as test returns value of true, statement block within loop executed As soon as test returns value of false, loop exits while loop syntax:
while <test> do <statement block> done
The Complete Guide to Linux System Administration 30

Adding Loops to a Script (continued)


break command
Exit from loop completely

continue command
Skip immediately to next iteration

The Complete Guide to Linux System Administration

31

Using Functions in a Script


Function
Named small shell script Can be referenced from other locations

To define function:
Follow name with ( ) Statements enclosed in braces { } considered part of function

The Complete Guide to Linux System Administration

32

Shell Script Debugging


Syntax error
Error in how statement is entered

Logic error
Error in what commands are trying to accomplish

Find and fix both types of errors


Use debugging features of shell

The Complete Guide to Linux System Administration

33

Shell Script Debugging (continued)


-n option
Check for syntax errors in script bash -n ./startnet Shell prints message when it finds syntax errors Does not actually execute any commands in script

-v option
Shell displays each line of script as it reads it

The Complete Guide to Linux System Administration

34

Using Shell Tracing


Shell trace
Displays each line of script on screen as it is executed Different from v option
Substitutes actual values for regular expressions and variables

Activated with -x option See if script is really using expected values

The Complete Guide to Linux System Administration

35

Debugging within a Script


set command with -x option
Turn on debugging within script Just at point where script appears to be working incorrectly
set -x commands to debug set +x

The Complete Guide to Linux System Administration

36

Other Programming Methods


Other types of scripts
Written using different computer languages Interpreted by different interpreters Specific syntax rules script must follow depend on interpreter

The Complete Guide to Linux System Administration

37

Other Scripting Languages


Different scripting languages used for different purposes By convention, scripts often use standardized file extensions to help users identify them perl programming language
Well suited to processing text strings Very popular as tool for managing data submitted by Web page forms

The Complete Guide to Linux System Administration

38

Other Scripting Languages (continued)


Common Gateway Interface (CGI) uses standard input and output channels to permit communications between two programs Tcl/Tk scripting language
Stands for tool command language/toolkit Executed by interpreter called wish

The Complete Guide to Linux System Administration

39

Other Scripting Languages (continued)


Python scripting language uses same Tk graphical programming toolkit as Tcl
Object-oriented language
Parts of Python program can be reused in another program with minimal effort

The Complete Guide to Linux System Administration

40

Other Scripting Languages (continued)

The Complete Guide to Linux System Administration

41

Compiled Languages
Linux kernel and utilities written using compiled languages Most widely used:
C C++

Collection of basic programming tools included with every Linux distribution

The Complete Guide to Linux System Administration

42

Compiled Languages (continued)


Writing simple computer program not hard
Write in text editor Compile to executable Give execute permission

Quickly becomes much more complicated Libraries


Collections of functions

The Complete Guide to Linux System Administration

43

Compiled Languages (continued)


Integrated Development Environments (IDEs)
Powerful tools to create large complex software projects Integrated in single interface:
Text editor Compiler with tracking of compilers output Debugger Commonly needed documentation

Several free and commercial IDEs available


The Complete Guide to Linux System Administration 44

Compiled Languages (continued)

The Complete Guide to Linux System Administration

45

Compiled Languages (continued)


Rapid Application Development (RAD) simplifies development of complex software projects by:
Providing prewritten modules Tracking multiple parts of project Reusing parts of software you have written

The Complete Guide to Linux System Administration

46

Summary
Shell scripts
Execute complex set of commands by entering single script name Uses keywords from programming language

Environment and positional variables often referenced in scripts if-then-else statement tests condition and executes statements if condition is present

The Complete Guide to Linux System Administration

47

Summary (Continued)
Loops using for and while
Repeatedly execute statement block

Complex scripts make extensive use of functions Shell scripts can be debugged using shell options Many scripting languages used on Linux systems Linux includes support for many computer languages

The Complete Guide to Linux System Administration

48

You might also like