0% found this document useful (0 votes)
72 views69 pages

Advanced SUSE Linux Enterprise Server Administration (Course 3038)

This document provides an overview of creating shell scripts in Linux. It covers basic script elements like variables, control structures like if/else and case statements, and loops. It also discusses more advanced techniques such as functions, reading user input, arithmetic operations, and using getopts to process command line options. The document is broken into chapters that begin with objectives and include examples and exercises to help learn shell scripting.

Uploaded by

yw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views69 pages

Advanced SUSE Linux Enterprise Server Administration (Course 3038)

This document provides an overview of creating shell scripts in Linux. It covers basic script elements like variables, control structures like if/else and case statements, and loops. It also discusses more advanced techniques such as functions, reading user input, arithmetic operations, and using getopts to process command line options. The document is broken into chapters that begin with objectives and include examples and exercises to help learn shell scripting.

Uploaded by

yw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 69

Advanced SUSE Linux

Enterprise Server
Administration (Course 3038)
Chapter 6
Create Shell Scripts

Objectives

Use Basic Script Elements


Use Variable Substitution Operators
Use Control Structures
Use Advanced Scripting Techniques
Learn About Useful Commands in Shell Scripts

Advanced SUSE Linux Enterprise Server Administratio

Use Basic Script Elements


Objectives

Flow Charts for Scripts


The Basic Rules of Shell Scripting
How to Develop Scripts That Read User Input
How to Perform Basic Script Operations with
Variables
How to Use Command Substitution
How to Use Arithmetic Operations

Advanced SUSE Linux Enterprise Server Administratio

Flow Charts for Scripts


Programming elements of a script
Often visualized by using program flow charts

Flow charts benefits


Force author to lay down the steps the script should
perform
Provide a clear symbolic outline of the algorithm

Advanced SUSE Linux Enterprise Server Administratio

Flow Charts for Scripts (continued)

Advanced SUSE Linux Enterprise Server Administratio

The Basic Rules of Shell Scripting


Shell script
ASCII text file
Contains commands to be executed in sequence
Permissions for script file must be set to r and x
chmod +x script.sh

Run shell script with sh script.sh


Create a /bin directory for scripts under each users
home directory
Add this directory to the users search path
export PATH=$PATH:~/bin

Advanced SUSE Linux Enterprise Server Administratio

The Basic Rules of Shell Scripting


(continued)
Add an .sh extension to the script filename
Make sure script filename is not identical to existing
commands
Elements of a script
Start
Commands
Stop

Advanced SUSE Linux Enterprise Server Administratio

The Basic Rules of Shell Scripting


(continued)

Advanced SUSE Linux Enterprise Server Administratio

Exercise 6-1 Produce Output from a


Script
In this exercise, you will produce output from a script
using the echo command

Advanced SUSE Linux Enterprise Server Administratio

How to Develop Scripts That Read


User Input
Command read
Used to create scripts that read user input
Takes a variable as an argument
And stores the read input in the variable

Variable can then be used to process the user input

Advanced SUSE Linux Enterprise Server Administratio

10

How to Develop Scripts That Read


User Input (continued)

Advanced SUSE Linux Enterprise Server Administratio

11

Exercise 6-2 Read User Input


In this exercise, you will use the read command in a
shell script to accept user input

Advanced SUSE Linux Enterprise Server Administratio

12

How to Perform Basic Script


Operations with Variables

Advanced SUSE Linux Enterprise Server Administratio

13

Exercise 6-3 Simple Operations with


Variables
In this exercise, you will practice performing simple
operations with variables

Advanced SUSE Linux Enterprise Server Administratio

14

How to Use Command Substitution


Command substitution
Output of a command is used in a shell command line
or a shell script

Example 1: printing output


echo "Today is `date +%m/%d/%Y`"

Example 2: assigning output to a variable


TODAY=`date +%m/%d/%Y`
echo "Today is $TODAY"

Advanced SUSE Linux Enterprise Server Administratio

15

Exercise 6-4 Use Command


Substitution
In this exercise, you will practice using command
substitution

Advanced SUSE Linux Enterprise Server Administratio

16

How to Use Arithmetic Operations


Bourne shell is limited in this regard
Can perform operations by relying on external
commands (such as expr)

Bash shell
Comes with built-in support for arithmetic operations
Limited in the following ways
Only supports operations with whole numbers
All values are signed 64-bit values

Needs to use external commands, such as bc, for


floating-point calculations
Advanced SUSE Linux Enterprise Server Administratio

17

How to Use Arithmetic Operations


(continued)
Use the external command expr
A=`expr $B + 10`

Use the Bash built-in command let


let A="$B + 10

Use arithmetic expressions inside parentheses or


brackets
A=$((B + 10)) or A=$[B + 10]

Use the built-in command declare


declare -i A
declare -i B
A=B+10

Advanced SUSE Linux Enterprise Server Administratio

18

Exercise 6-5 Use Arithmetic


Operations
In this exercise, you will practice using arithmetic
operations

Advanced SUSE Linux Enterprise Server Administratio

19

Use Variable Substitution Operators


Variable substitution operators
Used to assign different values to variables
Without having to rely on external commands

Advanced SUSE Linux Enterprise Server Administratio

20

Use Variable Substitution Operators


(continued)

Advanced SUSE Linux Enterprise Server Administratio

21

Exercise 6-6 Use Variable Substitution


In this exercise, you will practice using variable
substitution

Advanced SUSE Linux Enterprise Server Administratio

22

Use Control Structures


Objectives

Create Basic Branches with the if Command


Build Multiple Branches with a case Statement
Create Loops Using the while and until Commands
Process Lists with the for Loop
Interrupt Loop Processing

Advanced SUSE Linux Enterprise Server Administratio

23

Create Basic Branches with the if


Command
Basic usage of the if command
if condition
then
commands
fi

Optional else statement


if condition
then
command1
else
command2
fi

Advanced SUSE Linux Enterprise Server Administratio

24

Create Basic Branches with the if


Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

25

Create Basic Branches with the if


Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

26

Create Basic Branches with the if


Command (continued)
Example: birthday script
echo "Please enter your date of birth (YYYY-MM-DD, for
instance 1978-06-21): "
read BIRTHDAY
BIRTHDAY=${BIRTHDAY#*-}
TODAY= date + %m-%d
if test "$BIRTHDAY" = "$TODAY"
then
echo "Tada! Happy birthday to you! Nice presents
awaiting you ..."
else
echo "Sorry to disappoint you, no presents today ..."
fi

Advanced SUSE Linux Enterprise Server Administratio

27

Create Basic Branches with the if


Command (continued)
elif command
if condition1
then
command1
elif condition2
command2
else
command3
fi

Logical separators
&& and ||
Advanced SUSE Linux Enterprise Server Administratio

28

Create Basic Branches with the if


Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

29

Exercise 6-7 Use the if Command


In this exercise, you will practice using the if
command

Advanced SUSE Linux Enterprise Server Administratio

30

Build Multiple Branches with a case


Statement
case statement structure
case $variable in
expression1) command1;;
expression2) command2;;
esac

Example
#!/bin/bash
cat << EOF
Name me an animal and I will tell you how many legs
it
has!
EOF

Advanced SUSE Linux Enterprise Server Administratio

31

Build Multiple Branches with a case


Statement (continued)
Example (continued)
read CREATURE
case "$CREATURE" in
dog | cat | mouse ) echo "A $CREATURE has 4 legs."
;;
bird | human | monkey ) echo "A $CREATURE has 2 legs."
;;
spider ) echo "A $CREATURE has 8 legs."
;;
fly ) echo "A $CREATURE has 6 legs."
;;
* ) echo "I haven t the faintest idea how many
legs a(n) $CREATURE has."
;;
esac
exit 0

Advanced SUSE Linux Enterprise Server Administratio

32

Build Multiple Branches with a case


Statement (continued)

Advanced SUSE Linux Enterprise Server Administratio

33

Exercise 6-8 Use the case Command


In this exercise, you will practice using the case
command

Advanced SUSE Linux Enterprise Server Administratio

34

Create Loops Using the while and until


Commands
while loop
while condition
do
commands
done

until loop
until condition
do
commands
done

Advanced SUSE Linux Enterprise Server Administratio

35

Create Loops Using the while and until


Commands (continued)

Advanced SUSE Linux Enterprise Server Administratio

36

Exercise 6-9 Use the while and until


Command
In this exercise, you will practice using the while and
until commands

Advanced SUSE Linux Enterprise Server Administratio

37

Process Lists with the for Loop


for loop
for variable in element1 element2 element3
do
commands
done

Example
LIMIT=10
for ((a=1; a <= LIMIT ; a++))
do
echo -n "$a "
done

Advanced SUSE Linux Enterprise Server Administratio

38

Exercise 6-10 Use the for Loop


In this exercise, you will practice using the for loop

Advanced SUSE Linux Enterprise Server Administratio

39

Interrupt Loop Processing


continue command
Exits from the current iteration of a loop
Resumes with the next iteration of the loop

Example
for FILE in ls *.mp3
do
if test -e /MP3/$FILE
then
echo "The file $FILE exists."
continue
fi
cp $FILE /MP3
done

Advanced SUSE Linux Enterprise Server Administratio

40

Exercise 6-11 Interrupt Loop


Processing
In this exercise, you will practice using the continue
command to interrupt loop processing

Advanced SUSE Linux Enterprise Server Administratio

41

Use Advanced Scripting Techniques


Options
Use Shell Functions
Read Options with getopts

Advanced SUSE Linux Enterprise Server Administratio

42

Use Shell Functions


Use functions
To perform a task multiple times

Shell functions
Normally defined at the beginning of a script
Syntax
functionname () {
commands
commands
}

Advanced SUSE Linux Enterprise Server Administratio

43

Use Shell Functions (continued)


Generate a function
function functionname {
commands
commands
}

Example
# mcd: mkdir + cd; creates a new directory and
# changes into that new directory right away
mcd (){
mkdir $1
cd $1
}
...
mcd directory
...

Advanced SUSE Linux Enterprise Server Administratio

44

Exercise 6-12 Use Shell Functions


In this exercise, you will practice using shell
functions

Advanced SUSE Linux Enterprise Server Administratio

45

Read Options with getopts


getopts
Extracts options supplied to a script on the command
line

Shell command-line arguments


Command options prefixed with a -

Syntax
getopts optionstring variable
optionstring describes all options to be recognized
Option string is followed by a variable

Advanced SUSE Linux Enterprise Server Administratio

46

Read Options with getopts (continued)


Example
while getopts abc: variable
do
case $variable in
a ) echo "The option -a was used." ;;
b ) echo "The option -b was used." ;;
c ) option_c="$OPTARG"
echo "Option c has been set." ;;
esac
done
echo $option_c

Advanced SUSE Linux Enterprise Server Administratio

47

Exercise 6-13 Use the getopts


Command
In this exercise, you will practice using the getopts
command

Advanced SUSE Linux Enterprise Server Administratio

48

Learn About Useful Commands in


Shell Scripts
Objectives

Use the cat Command


Use the cut Command
Use the date Command
Use the echo Command
Use the grep and egrep Commands
Use the sed Command
Use the test Command
Use the tr Command

Advanced SUSE Linux Enterprise Server Administratio

49

Use the cat Command


Combined with the << (here) operator
Outputs several lines of text from a script

Interactive use
Mostly run with a filename as an argument
Prints the file contents on standard output

Advanced SUSE Linux Enterprise Server Administratio

50

Use the cut Command


Cuts out sections of lines from a file
Specified section is printed on standard output
Use cut -f to cut out text fields
cut -c works with the specified characters

You can specify single sections (characters or fields)


Or several sections

Default delimiter to separate fields from each other


is a tab
Specify a different field separator with the -d option
Advanced SUSE Linux Enterprise Server Administratio

51

Use the date Command


Used to obtain a date or time string
For further processing by a script

Examples
date -I
2007-09-03
date +%m-%d %H:%M
09-03 14:19
date +%D, %r
09/03/07, 02:19:58 PM
date +%A, %e. %B %Y
Friday, 3. September 2007

Advanced SUSE Linux Enterprise Server Administratio

52

Use the echo Command


Prints text lines on standard output
Line break is inserted automatically after each line
With the -e option, echo accepts a number of
additional options

Special sequences
\a outputs an alert
\c do not add a new line
\n add a new line

Advanced SUSE Linux Enterprise Server Administratio

53

Use the grep and egrep Commands


Used to search files for certain patterns
Syntax
grep searchpattern filename ...

Commands support various options


Example
tux@DA1:~> egrep (b|B)lurb file*
bash: syntax error near unexpected token |
tux@DA1:~> egrep "(b|B)lurb" file*
file1:blurb
file2:Blurb

Advanced SUSE Linux Enterprise Server Administratio

54

Use the sed Command


Sed is a stream editor
Editor used from the command line rather than
interactively

Syntax
sed editing-command filename

Available editing commands

d: Delete
s: Substitute (replace)
p: Output line
a: Append after

Advanced SUSE Linux Enterprise Server Administratio

55

Use the sed Command (continued)


Command-line options include
-n, --quiet, --silent
-e command1 -e command2 ....
-f filename

Supports regular expressions

Advanced SUSE Linux Enterprise Server Administratio

56

Use the sed Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

57

Use the test Command


Used to compare values
And to check for files and their properties

If a tested condition is true


test returns an exit status of 0
Otherwise, test returns an exit status of 1

Syntax
test condition

Testing whether a file exists


See Table 6-3
Advanced SUSE Linux Enterprise Server Administratio

58

Use the test Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

59

Use the test Command (continued)


Comparing two files
See Table 6-4

Comparing two integers


See Table 6-5

Testing strings
See Table 6-6

Advanced SUSE Linux Enterprise Server Administratio

60

Use the test Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

61

Use the test Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

62

Use the test Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

63

Use the test Command (continued)


Combined tests
See Table 6-7

Advanced SUSE Linux Enterprise Server Administratio

64

Use the test Command (continued)

Advanced SUSE Linux Enterprise Server Administratio

65

Use the tr Command


Used to translate (replace) or delete characters
Reads from standard input
Prints the result on standard output

Syntax
tr set1 set2

Examples

cat text-file | tr a-z A-Z


tr -d set1
VAR=echo $VAR | tr -d %
tr -s set1 char

Advanced SUSE Linux Enterprise Server Administratio

66

Summary
Shell scripts contain Linux commands that execute in
the shell
Before creating a shell script
Use flow chart symbols to plan its flow control

Shell scripts start with a shebang


Denotes the shell that is called to run the commands

User input may be obtained using the read command


echo command sends output to the terminal screen

Backticks are used to perform command substitution


Advanced SUSE Linux Enterprise Server Administratio

67

Summary (continued)
Arithmetic operations performed with the expr,
declare, and let commands
Value of a variable may be modified using a variable
substitution operator
Flow of a program may be modified using one of
several control structures

if, case
while, until, for
continue, break
&&, || operators

Advanced SUSE Linux Enterprise Server Administratio

68

Summary (continued)
You can create reusable subroutines within shell
scripts called functions
getopts command
May be used within a shell script to obtain the options
specified on the command line

Most common Linux commands used within a shell


script include:
cat, cut, date, echo, grep, egrep, sed, test, and tr

Advanced SUSE Linux Enterprise Server Administratio

69

You might also like