(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration...

30
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana University

Transcript of (A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration...

(A Very Short)Introduction to Shell Scripts

CSCI N321 – System and Network Administration

Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana University

Section Overview

Comments and Script Headers

Variables

Flow Control

Loops

References

Linux System Administration

Chapter 14

CQU COIT 13146 System Administration Course TextbookChapter 9

Lectures2002 #8

Why Learn Scripting?

/bin/sh always thereUnderstand/Modify Existing System Scripts RC Startup Scripts Daemon Startup Scripts

Automate repetitive tasksGreat for small tools

Writing/Debugging Scripts

Know how to do job manually firstWrite in small (logical) partsTest each part before continuing Print modified variables Print command lines to be executed Never work on production data

Comment code!!!

Starting Scripts

Passed as input to a shell Example: /bin/bash mysript

Run directly from the command line First line of script (i.e: #!/bin/bash) Script must have execute bits set $PATH considerations

Commenting code

Anything following ‘#’ is considered a comment and ignoredScript Header Tells what the script does Common Entries:

• Author• Date written• Program name• Command line usage

• Purpose• Files used• Notes/features• Revision History

Argument Variables

VariableVariable PurposePurpose

$0 Name of the program

$1 - $9 Command line arguments

$# Number of Arguments

$* All arguments as 1 word

$@ Each argument is a word

Other Special Variables

VariableVariable PurposePurpose

$$ PID number of script

$!PID number of parent process

$?Exit status of script(Checked by parent)

Basic Input

read variable [ < filename ]

Examples: read ANS read LINE < file

(only reads first line)

Basic output

echo [ -n ] [ -e ] “string”

-n : No new line-e : Allow backslash options

Example: echo –n “Enter your name: “

Backslash OptionsCharacterCharacter PurposePurpose

\a Alert (bell)

\b Backspace

\c Don’t display trailing newline

\n Newline

\r Carriage return

\t Horizontal Tab

\v Vertical Tab

\\ Backslash

\### ###: ascii value of character

Expression Evaluation

expr command Math expressions ( +, -, *, /, % ) String expressions (match, substring,

etc.) Logic expressions ( &, |, =, etc.)

Example: COUNT=`expr $COUNT + 1`

Flow Control

Need to determine which commands to run based on one or more conditionsUseful to catch errorsProvides flexibility in codeClassic if-then-else model

If-Then condition

Basic decision construct

if condition

then

commands

fi

String Tests

ExpressionExpression True if…True if…

-z string Length of string is 0

-n string Length of string is not 0

string1 = string2If the 2 strings are identical

string1 != string2If the 2 strings are different

string If string is not NULL

Numeric Tests

ExpressionExpression True if…True if…

int1 –eq int2 int1 equals int2

int1 –ne int2 int1 and int2 not equal

int1 –gt int2 int1 > int2

int1 –ge int2 int1 >= int2

int1 –lt int2 int1 < int2

int1 –le int2 int1 <= int2

File Tests

ExpressionExpression True if…True if…

-r file File exists and readable

-w file File exists and writable

-x file File exists and executable

-f file File exists and is a regular file

-d file File exists and is a directory

-h file File exists and is a symbolic link

-p file File exists and is a named pipe

File Tests (Con’t.)

ExpressioExpressionn

True if…True if…

-c file File exists and is a character device

-b file File exists and is a block device

-u file File exists and is SUID

-g file File exists and is SGID

-k file File exists and sticky bit set

-s file File exists and size > 0 bytes

Logic Operators

ExpressionExpression PurposePurpose

! Negates the expression

-a AND

-o OR

( expression ) Groups the expression

If-Then-Else condition

if condition

then

commands

else

commands

fi

If-Then-Else If condition

if condition

then

commands

elif condition

then

commands

fi

Case condition

Perform a range of tests on a variable

case variable in

pattern1) commands ;;

pattern2) commands ;;

esac

*) matches all other cases

Loops

Need to run block of code more than onceModes Repeat a set number of times Repeat while a condition is true Repeat until a condition is true

for loop

Repeat for each variable in list

for variable in variable_list

do

commands

done

while loop

Repeat until condition is false

while [ condition ]

do

commands

done

Reading Files

Read a file one line at a time

while read LINE

do

echo $LINE

done < $FILENAME

do-until loop

Repeat until condition is true

until [ condition ]

do

commands

done

Escaping out of loopsSometimes you need to exit loop early

Error conditions Special conditions

break commandExample:while [ 1 ]do

echo –n “Done? “read ANSif [ $ANS = “y” ]thenbreakfi

done

Other scripting languages

Perl Very popular among sysadmins Many modules available

TCL/TKExpectPython