28
Day 8,9,10 Day 8,9,10 COP 3502 COP 3502 Introduction to Introduction to Shell Scripts Shell Scripts David A. Gaitros David A. Gaitros Department of Department of Computer Science Computer Science Florida State Florida State University University

Day 8,9,10 COP 3502 Introduction to Shell Scripts David A. Gaitros Department of Computer Science Florida State University

Embed Size (px)

Citation preview

Day 8,9,10Day 8,9,10COP 3502 COP 3502

Introduction to Introduction to Shell ScriptsShell Scripts

David A. GaitrosDavid A. Gaitros

Department of Department of Computer ScienceComputer Science

Florida State Florida State UniversityUniversity

What is a shell What is a shell script? script?

• A group of UNIX A group of UNIX commands along with a commands along with a few programming few programming constructs placed in a file constructs placed in a file that is executable. Must that is executable. Must like a program. like a program.

• Used when a function Used when a function needs to be completed needs to be completed over and over again. over and over again.

• Your startup scripts are Your startup scripts are shell scripts. shell scripts.

Simple Shell Simple Shell ScriptsScripts

• The following text is The following text is placed in a file called placed in a file called simplesimple

# A Comment starts with # A Comment starts with an #an #

calcal

datedate

whowho

How to run a shell How to run a shell scriptscript

• There are two waysThere are two ways– 1. Use the (sh) command1. Use the (sh) command

sh simple <r>sh simple <r>

– 2. Change the permissions 2. Change the permissions to executable and just to executable and just enter the file nameenter the file namechmod 755 simple <r>chmod 755 simple <r>

chmod u+rwx,a+x,g+e simple chmod u+rwx,a+x,g+e simple <r><r>

simple <r>simple <r>

The Shell as a The Shell as a programming programming

languagelanguage• variablesvariables

– environmentenvironment– user createduser created– positional parameterspositional parameters

• input/output functionsinput/output functions• arithmetic operationsarithmetic operations• conditional expressionsconditional expressions• selection structuresselection structures• repetition structuresrepetition structures

VariablesVariables

• Environment - Special Environment - Special shell variables, keyword shell variables, keyword variables, predefined variables, predefined variables, or standard shell variables, or standard shell variables. variables. – Examples include TERM, Examples include TERM,

HOME, MAIL, PATH, etc. HOME, MAIL, PATH, etc. – They exist and you can They exist and you can

change them but you do not change them but you do not initially create them. initially create them.

Unix Shell StuffUnix Shell Stuff

• Standard Input and OutputStandard Input and Output– Standard input - stdinStandard input - stdin– Standard output - stdoutStandard output - stdout– Standard error - stderrStandard error - stderr

• RedirectionRedirection– ls -al > directory.out<r>ls -al > directory.out<r>– ls -al >> directory.out <r># ls -al >> directory.out <r>#

Appends Appends – mail gaitrosd < this.text <r>mail gaitrosd < this.text <r>

Unix Shell Stuff Unix Shell Stuff

• Pipes - The output of one Pipes - The output of one command is input to command is input to another. another.

ls -al | more <r>ls -al | more <r>

# The output of the ls # The output of the ls command is given to the command is given to the more command with the more command with the pipe (|) symbol. pipe (|) symbol.

• You can also group You can also group commands on one line by commands on one line by separating them with a separating them with a semicolon (;)semicolon (;)

Unix Shell StuffUnix Shell Stuff

• teetee• A A teetee allows you to save allows you to save

the output of one the output of one command while also command while also making it input to another:making it input to another:

ls -al | tee output.dat | more ls -al | tee output.dat | more <r> <r>

Unix Shell StuffUnix Shell Stuff• Wildcards - A single character that Wildcards - A single character that

stands for a group of characters. stands for a group of characters. • Let us say that you wanted to list Let us say that you wanted to list

all of the files that ended with all of the files that ended with .out.outls -al *.out <r> ls -al *.out <r> • You can put wildcards anywhereYou can put wildcards anywherels -al *fall*.out <r> ls -al *fall*.out <r> This gives us all the files that have This gives us all the files that have

the word fall embedded in it that the word fall embedded in it that end in .out. end in .out.

• The ? is also a wildcard but it only The ? is also a wildcard but it only does one character at a time. For does one character at a time. For instance: instance:

ls -al ?ello.out <r> ls -al ?ello.out <r> This lists all the files starting with This lists all the files starting with

any character and ending in any character and ending in ello.out. ello.out.

Unix Shell StuffUnix Shell Stuff

• Special Characters that have Special Characters that have special meaning:special meaning:

• & * \ | [ ] { } $ < > ( ) # ? ' " / ; & * \ | [ ] { } $ < > ( ) # ? ' " / ; ^ ! ~ % `^ ! ~ % `

• To print these characters you To print these characters you must precede them each time must precede them each time with a backslash (\) usually found with a backslash (\) usually found below the pipe(|) symbol on the below the pipe(|) symbol on the keyboard. keyboard.

echo "what time is it\?" <r> echo "what time is it\?" <r> • It only works on a single It only works on a single

character and you must put one character and you must put one in front of every special character in front of every special character you want to print. you want to print.

• Backquotes ( also called grave Backquotes ( also called grave accent marks). The backquotes accent marks). The backquotes run a unix command inside the run a unix command inside the shell. shell.

Unix Shell StuffUnix Shell Stuff

QuoteQuote EffiectEffiect

\\ Cancels the special Cancels the special meaning of a single meaning of a single character inside a character inside a stringstring

'string''string' Cancels the special Cancels the special meaning of any special meaning of any special characters inside the characters inside the stringstring

"string""string" Cancels the special Cancels the special meaning of any special meaning of any special characters inside the characters inside the string except $, ` `, string except $, ` `, and \and \

`string``string` Run any command in Run any command in the string. Output the string. Output replaces `string`. Note replaces `string`. Note these ` are backquotes. these ` are backquotes.

VariablesVariables• User Created VariablesUser Created Variables

– Creating user variables is easy. You Creating user variables is easy. You just specify a name not already in just specify a name not already in use and assign a value to it. Use the use and assign a value to it. Use the set set command. command.

set stuff = ~gaitrosd/public_html<r>set stuff = ~gaitrosd/public_html<r>– To use the value inside the variable To use the value inside the variable

you place a $ in front of it. you place a $ in front of it. ls -al $stuff <r>ls -al $stuff <r>

NOTE: typically, user defined NOTE: typically, user defined variables are in lower case to variables are in lower case to distinguish them from standard distinguish them from standard shell variables. shell variables.

Positional Positional ParametersParameters

• Positional parameters are also called Positional parameters are also called read-only. They are numbered 1,2,3,read-only. They are numbered 1,2,3,….9. and correspond to the ….9. and correspond to the parameters entered as part of the parameters entered as part of the shell command. shell command.

• $0 is always the shell script $0 is always the shell script command. command.

• Each parameter is identified by a Each parameter is identified by a space separation at the UNIX space separation at the UNIX prompt. prompt.

• The $# is defined in the shell The $# is defined in the shell programming structure as programming structure as containing the number of containing the number of parameters. It starts counting with parameters. It starts counting with the actual first parameter. the actual first parameter.

• The $* is the string that contains all The $* is the string that contains all the arguments. the arguments.

Positional Positional ParametersParameters

• Here is an example Here is an example program called echo.argsprogram called echo.args

# Comment Line # Comment Line

echo "Welcome to the echo shell program"echo "Welcome to the echo shell program"

echo "This is an example of positional echo "This is an example of positional parameters"parameters"

echo "This program can handle up to nine (9) echo "This program can handle up to nine (9) parameters"parameters"

echo "You have typed $# arguments"echo "You have typed $# arguments"

Demonstration of shell scriptDemonstration of shell script

Input/Output Input/Output FunctionsFunctions

• As you have seen, the As you have seen, the echoecho command allows you to output command allows you to output items to standard output. items to standard output.

• The The readread command allows you command allows you to input simple items into the to input simple items into the shell script. shell script.

#!/bin/sh#!/bin/sh

#Illustrates the use of positional parameters, user #Illustrates the use of positional parameters, user

# defined variables# defined variables

# and the read command# and the read command

echo 'What is your name'echo 'What is your name'

read nameread name

echo "Well, $name, you typed in $# arguments"echo "Well, $name, you typed in $# arguments"

echo "They are: $*"echo "They are: $*"

• Demonstration: Demonstration:

Set CommandSet Command

• Assume we have the program Assume we have the program as follows in a file called as follows in a file called setdate. The set command setdate. The set command executes the date command executes the date command and automatically assigns and automatically assigns the output to the the output to the positional parameters. positional parameters.

set `date`set `date`echo "Time: $4 $5"echo "Time: $4 $5"echo "Day: $1"echo "Day: $1"echo "Date: $3 $2 $6"echo "Date: $3 $2 $6"

Demonstration: Demonstration:

Arithmetic Arithmetic OperationsOperations

• The shell is not intended to The shell is not intended to do any extensive do any extensive mathematics. You should mathematics. You should only perform simple integer only perform simple integer arithmetic. (*) (+) (-) (/) (%)arithmetic. (*) (+) (-) (/) (%)

• Use the Use the expr expr UNIX utility. UNIX utility. • example: example:

sum = ` expr $1 + $2` <r>sum = ` expr $1 + $2` <r>

echo "$1 + $2 is equal to echo "$1 + $2 is equal to $sum"<r>$sum"<r>

# Note the backquotes in the # Note the backquotes in the first line of the program. first line of the program.

Conditional Conditional ExpressionsExpressions

if if conditional expression conditional expression then then commandscommandsfi fi

• Most of the time, the conditional Most of the time, the conditional expression will need the use of theexpression will need the use of the test test command.command.

• Note also commands and the Note also commands and the then then must must start on separate lines. start on separate lines.

if if conditional expressionconditional expressionthen then commandscommandselif elif conditional expression conditional expression then then commandscommandselseelse commandscommandsfi fi

Conditional Conditional ExpressionsExpressions

ArgumentArgument Test is True if: Test is True if:

-d-d filefile filefile is a directory is a directory

-f-f filefile filefile is an ordinary file is an ordinary file

-r -r filefile file file is readableis readable

-s -s filefile file file size is greater than size is greater than zerozero

-w -w filefile file file is writableis writable

-x -x filefile filefile is executable is executable

n1n1 -eq-eq n2n2 Integer n1 is equal to n2Integer n1 is equal to n2

n1n1 -ge-ge n2n2 Integer n1 is > = n2Integer n1 is > = n2

n1n1 -le-le n2n2 Integer n1 is <= n2Integer n1 is <= n2

n1n1 -ne-ne n2n2 Integer n1 is not equal to Integer n1 is not equal to n2n2

n1n1 -lt-lt n2n2 Integer n1 is less then n2Integer n1 is less then n2

s1s1 == s2s2 String s1 is equal to string String s1 is equal to string s2s2

s1s1 !=!= s2s2 String s1 is not equal to String s1 is not equal to string s2string s2

If statement If statement example - tgifexample - tgif

• set `date`set `date`• if test $1 = Friif test $1 = Fri• thenthen• echo "TGIF"echo "TGIF"• elif test $1 = Sat || test $1 = Sunelif test $1 = Sat || test $1 = Sun• thenthen• echo "Yeah it is the weekend"echo "Yeah it is the weekend"• elif test $1 = Monelif test $1 = Mon• thenthen• echo " Monday stinks "echo " Monday stinks "• elif test $1 = Tueelif test $1 = Tue• thenthen• echo "Thank goodness it is not Monday"echo "Thank goodness it is not Monday"• elif test $1 = Wedelif test $1 = Wed• thenthen• echo "Hump day"echo "Hump day"• else echo "Survivor Party Night"else echo "Survivor Party Night"• fifi• echo "$*" echo "$*"

The Case The Case StatementStatement

casecase word word inin

pattern1) command(s) pattern1) command(s) ;;;;

pattern2) commands(s) pattern2) commands(s) ;;;;

. . .. . .

patternN) command(s) patternN) command(s) ;;;;

esacesac## Commands are seperated by semicolongsCommands are seperated by semicolongs

# The group of commands is ended by two # The group of commands is ended by two semicolons. semicolons.

# The OR symbol is just one vertical line (|)# The OR symbol is just one vertical line (|)

# the astrik (*) marks the default case. # the astrik (*) marks the default case.

Case Statement Case Statement ExampleExample

set `date`set `date`case $1 incase $1 inMon)echo "I do not wake up on Mon)echo "I do not wake up on

Monday";;Monday";;Tue) echo "Nothing good on TV might Tue) echo "Nothing good on TV might

as well study";;as well study";;Wed) echo "Wednesdays are Wed) echo "Wednesdays are

useless";;useless";;Thu) echo "Watch Alias tape, Love Thu) echo "Watch Alias tape, Love

Jenny Garner";;Jenny Garner";;Fri) echo "Pizza Night";;Fri) echo "Pizza Night";;Sat) echo "Cartoon day";;Sat) echo "Cartoon day";;*) echo "It is Sunday";*) echo "It is Sunday"; echo "I can sleep late and tape echo "I can sleep late and tape

Alias";;Alias";;esacesac

For LoopsFor Loops

forfor variablevariable [in[in listlist]]

do do

command(s)command(s)

donedone

Example: Example:

for test in "one" "two" for test in "one" "two" "three""three"

dodo

echo "$test"echo "$test"

donedone

While loopsWhile loops

whilewhile condition condition

dodo

command(s)command(s)

donedone

Note: Note: condition condition is the same is the same syntax and behavior as in syntax and behavior as in an an ifif statement. statement.

Until LoopsUntil Loops

untiluntil conditioncondition

dodo

command(s)command(s)

donedone

Note: Note: condition condition is the same is the same syntax and behavior as in syntax and behavior as in an an ifif statement. statement.

Some useful scriptsSome useful scriptsSource: Just Enough Unix by Paul Source: Just Enough Unix by Paul

Anderson. Modified by David Anderson. Modified by David GaitrosGaitros

# Change a files permissions to# Change a files permissions to# executable# executable# File name is chex. # File name is chex. # Pass in the file as a parameter# Pass in the file as a parameterif test -f $1 if test -f $1 then then chmod u+x $1chmod u+x $1 echo "File $1 is executable"echo "File $1 is executable" ls -l $1ls -l $1 elseelse echo "$1 is not a file"echo "$1 is not a file"fifi

Some useful scriptsSome useful scriptsSource: Just Enough Unix by Source: Just Enough Unix by Paul Anderson. Modified by Paul Anderson. Modified by

David GaitrosDavid Gaitros

#Removing files safely#Removing files safely

# File name is DELETE# File name is DELETE

set filename = $1set filename = $1

if test ! -f $filenameif test ! -f $filename

then echo "Not a valid file"then echo "Not a valid file"

else else

echo "Do you really want to delete echo "Do you really want to delete $filename (y/n)"$filename (y/n)"

read choiceread choice

if test $choice = y || test $choice = Y if test $choice = y || test $choice = Y

then then

rm $filenamerm $filename

echo "\"$filename\"deleted."echo "\"$filename\"deleted."

elseelse

echo "\"$filename\" not deleted."echo "\"$filename\" not deleted."

fifi

fifi