Topic 2: Bash Shell...

36
K24: Προγραμματισμός Συστήματος Topic 2: Bash Shell Programming * *Ευχαριστίες στους Τάκη Σταματόπουλο, Αλέξη ∆ελή, και Αντώνη ∆ελιγιαννάκη

Transcript of Topic 2: Bash Shell...

Page 1: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος

Topic 2: Bash Shell Programming*

*Ευχαριστίες στους ΤάκηΣταµατόπουλο, Αλέξη ∆ελή, και Αντώνη ∆ελιγιαννάκη

Page 2: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 2

Προγραµµατισµός Bash κελύφους

Πιο εύκολο από C κέλυφοςInherits many features from C & Korn shellsMost popular shell on Linux systemsLinux most popular “Unix” system

Ακολουθία από εντολές# δηλώνει σχόλιοΠρώτη γραµµή #!/bin/bash

Μεταβλητές, συνθήκες∆οµές ελέγχουΟρίσµατα προγράµµατοςΑριθµητικές πράξεις

Και άλλα πολλά…

Κατεβάστε το bash-scripts.tar από τη σελίδατου µαθήµατος

Page 3: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 3

Παράµετροι Προγράµµατος– Πρόγραµµα parameters

mema@bowser> ./parameters a b c d e f g h i j kNumber of input parameters = 11Program Name = ./parametersOther Parameters = a b c d e f g h i a0 a1Other Parameters = a b c d e f g h i j kAll Arguments = a b c d e f g h i j kmema@bowser>

#!/bin/bash # all scripts start like this

#This is a comment

#will give 11 arguments to this program # a b c d e f g h i j k

echo Number of input parameters = $# # 11echo Program Name = $0 # ./parameters

echo Other Parameters = $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11#Other Parameters = a b c d e f g h i a0 a1

echo Other Parameters = $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11}#Other Parameters = a b c d e f g h i j k

echo All Arguments = $*#All Arguments = a b c d e f g h i j k

Bash script must be executable to run. Use chmod +x shell_script_name.

Page 4: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 4

Περί Μεταβλητών -Πρόγραµµα variables

#!/bin/bash

# Erwthsh: POTE DEN BAZOUME TO '$' mprosta se mia metablhth?# Apanthsh: Otan ths ana8etoume timh

#NEVER USE SPACES BEFORE AND AFTER = IN ASSIGNMENTSa=2334 # Integer - Only digitsecho a # aecho $a # 2334

hello="A B C D"echo $hello # A B C Decho "$hello" # A B C D# Ta dipla eisagwgika diathroun ta polla kena

echo '$hello' # $hello# Ta mona eisagwgika apenergopoioun thn anafora timhs me $

echo -n "Enter \"b\" " # Grafw hey thereread becho "The value of \"b\" is now $b"# The value of "b" is now hey there

echo ${PATH} # SWSTO - Metablhth periballontos PATH

mema@bowser> ./variables a2334A B C DA B C D$helloEnter "b" hey thereThe value of "b" is now hey there/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/gamesmema@bowser>

$PATH or ${PATH} if easier to read

Page 5: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 5

Αριθµητικές Πράξεις -Πρόγραµµα arithmetics

Πολλές επιλογές:

•Για απλές πράξεις, οι εντολές let και expr.

•Για δεκαδικούς, η εντολή bc

#!/bin/bash

a=2334 let b=a+3 # isxyei kai to let b=$a+3let "c = a+3"let "d = a+ 3“ #eite me eite xwris kena

z=$(($a+3))‏y=$((a+3)) # Epishs swsto

k=`expr $a + 3` # Xrhsh entolhs expr

echo $a $b $c $d $k $z $y#2334 2337 2337 2337 2337 2337 2337

mema@bowser> ./arithmetics2334 2337 2337 2337 2337 2337 2337mema@bowser>

Page 6: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 6

Εντολή expr -Πρόγραµµα myexpr

#!/bin/bash

# PROSOXH: APAITOYNTAI KENAa=`expr 3 + 5`; echo $a # 8 a=`expr 5 % 3`; echo $a # 2 a=`expr 5 / 3`; echo $a # 1 # a=`expr 1 / 0` # Epistrefei sfalmaa=`expr 5 \* 3`; echo $a # 15. Me to expr, ston pollaplasiasmo \* a=`expr $a + 5`; echo $a # Idio me let a=a+5

string=EnaMegaloStringecho "String is: ${string}"position=4length=6z=`expr substr $string $position $length`#E3agei length xarakthres apo to string.#3ekinaei apo th 8esh position

echo "Substring is: $z" # Megalo

mema@bowser> myexpr8211520String is: EnaMegaloStringSubstring is: Megalomema@bowser>

Page 7: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 7

Πράξεις δεκαδικών µε bc – Πρόγρ. mybc

#!/bin/bash

# EPITREPEI ARI8MHTIKES PRA3EIS SE DEKADIKOUSa=100.19b=$(echo "scale=3; $a/100" | bc)‏# scale ka8orizei dekadika pshfia

echo b = $b # b = 1.001

#perform inequality testsA=0.04B=0.03let "comp=`echo $A-$B\>0 | bc`“echo $comp # 1

let "comp=`echo $B-$A\>0 | bc`"echo $comp # 0

mema@bowser> ./mybcb = 1.00110mema@bowser>

Με την echo στέλνουµε ως όρισµαστη bc: 0.04-0.03>0 καιεπιστρέφει 0/1.

Page 8: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 8

Τιµή εξόδου –Πρόγραµµα exitStatus

#!/bin/bash

# To $? epistrefei ton kwdiko e3odou ths teleytaias# entolhs pou ektelesthkeecho helloecho $? # 0 : epitygxhmenh ektelesh

lsdlsd # agnwsth entolhecho $? # 127 - genikws mh mhdenikh se sfalma

echo

exit 113 # Prepei na einai 0-255

mema@bowser> ./exitStatushello0./exitStatus: line 8: lsdlsd: command not found127

mema@bowser>

Page 9: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 9

Συνθήκες

Στη γενική µορφή σε δύο είδη:[ συνθήκη ελέγχου ] ήtest συνθήκη ελέγχου

Πιο σπάνια και αριθµητικές συνθήκες, συνθήκες (()) …

The base for the if construction in bash is:

if [expression]; thencode if ‘expression’ is true.fi

Example:#!/bin/bash if [ "foo" = "foo" ]; then

echo expression evaluated as truefi

Page 10: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 10

Αριθµητικές Συνθήκες –Πρόγραµµα arithmeticTests

#!/bin/bash

# Arithmetic tests.# The (( ... )) construct evaluates and tests # numerical expressions.# Exit status opposite from [ ... ] construct!

(( 0 ))echo "Exit status of \"(( 0 ))\" is $?." # 1(( 1 ))echo "Exit status of \"(( 1 ))\" is $?." # 0(( 5 > 4 )) # trueecho "Exit status of \"(( 5 > 4 ))\" is $?." # 0(( 5 > 9 )) # falseecho "Exit status of \"(( 5 > 9 ))\" is $?." # 1(( 5 - 5 )) # 0echo "Exit status of \"(( 5 - 5 ))\" is $?." # 1(( 5 / 4 )) # Division o.k. Result > 1.echo "Exit status of \"(( 5 / 4 ))\" is $?." # 0(( 1 / 2 )) # Division result < 1. Division is rounded off to 0. echo "Exit status of \"(( 1 / 2 ))\" is $?." #1

(( 1 / 0 )) 2>/dev/null # Illegal division by 0.# ^^^^^^^^^^^echo "Exit status of \"(( 1 / 0 ))\" is $?." # 1# What effect does the "2>/dev/null" have?# What would happen if it were removed?# Try removing it, then rerunning the script.exit 0

Page 11: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 11

Συνθήκες Αρχείων –Πρόγραµµα fileTests

mema@bowser> ls moreExprmoreExpr*mema@bowser> ./fileTests moreExprRegular FileI can read this file!!!mema@bowser> ls -l moreExpr-rwxr-xr-x 1 mema mema 440 Oct 11 09:37 moreExpr*mema@bowser>

#!/bin/bash

if [ -e $1 ] # exists filethen if [ -f $1 ] # is a regular file

then echo Regular Filefi

fi# Omoia, to -d elegxei an prokeitai gia katalogo

if [ -r $1 ] # have read rightsthen echo I can read this file!!!

fi# Omoia to -w kai -x

Page 12: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 12

Συνθήκες Ακεραίων

Μικρότερο ή ίσο((“$a” <= “$b”))

-leif [ “$a” –le “$b” ]

Μικρότερο((“$a” < “$b”))‏

-ltif [ “$a” –lt “$b” ]

Μεγαλύτερο ήίσο

((“$a” >= “$b”))

-geif [ “$a” –ge “$b” ]

Μεγαλύτερο((“$a” > “$b”))

-gtif [ “$a” –gt “$b” ]

Άνισα-neif [ “$a” –ne “$b” ]

Ίσα-eqif [ “$a” –eq “$b” ]

Page 13: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 13

Συνθήκες Strings (πάντα ναχρησιµοποιείτε εισαγωγικά)

Όχι null-nif [ -n “a” ]

Null (µέγεθος 0)-zif [ -z “a” ]

Μεγαλύτεροαλφαβητικά

>if [ “$a” \> “$b” ]

Μικρότεροαλφαβητικά

<if [ “$a” \< “$b” ]

∆ιαφορετικά!=if [ “$a” != “$b” ]

Ίσα==if [ “$a” == “$b” ]

Ίσα=if [ “$a” = “$b” ]

Page 14: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 14

Λογικές Συνθήκες

Λογικό OR-oif [ “$a” –o “$b” ]

Λογικό AND-a if [ “$a” –a “$b” ]

Λογικό NOT! if [ ! –f “file” ]

Page 15: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 15

∆οµή Ελέγχου if

if <συνθήκη1>thenεντολές

elif <συνθήκη2>thenεντολές

…elseεντολές

fi

Προφανώς τα τµήµατα elif και else είναιπροαιρετικά

Page 16: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 16

∆οµή Ελέγχου case

case “$variable” in“$condition1” )εντολές….;;…“$conditionN” )εντολές….;;esac

Page 17: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 17

Παράδειγµα ∆οµής case –Πρόγραµµα math

Πρόγραµµα που εκτελεί απλές πράξεις µεταξύ 2 ακεραίων. #!/bin/bash## Usage: math n1 op n2#case "$2" in+) echo "Addition requested."

echo "$1 + $3 = `expr $1 + $3`" ;;-) echo "Substraction requested."

echo "$1 - $3 = `expr $1 - $3`" ;;\*) echo "Multiplication requested."

echo "$1 * $3 = `expr $1 \* $3`" ;;/) echo "Division requested."

echo "$1 / $3 = `expr $1 / $3`" ;;%) echo "Modulo arithmetic requested."

echo "$1 % $3 = `expr $1 % $3`" ;;*) echo "Unknown operation specified." ;;esac

mema@bowser> ./math 34 + 56Addition requested.34 + 56 = 90mema@bowser> ./math 34 - 23.3Subtraction requested.

Expr: non-numeric argument Γιατί;34 – 23.3 =mema@bowser> ./math 34 -23Unknown operation specified.mema@bowser> ./math 34 - 23Substraction requested.34 - 23 = 11mema@bowser> ./math 34 * 2Unknown operation specified. Γιατί;mema@bowser> ./math 34 \* 2Multiplication requested.34 * 2 = 68mema@bowser>

Page 18: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 18

∆οµή for –Πρόγραµµα forLoops

#!/bin/bash

for koko in 1 2 3 4 5doecho $koko

#Ektypwsh se diaforetikes grammesdone

for koko in "1 2 3 4 5"doecho $koko

#Ektypwsh se mia grammhdone

NUMS="1 2 3 4 5"for koko in $NUMSdoecho $koko

#Ektypwsh se diaforetikes grammesdone

for koko in `echo $NUMS`doecho $koko

#Ektypwsh se diaforetikes grammesdone

LIMIT=8#Diples parentheseis, LIMIT xwris $for ((koko=1; koko <= LIMIT; koko++)) doecho $koko "loop me limit"

#Ektypwsh se diaforetikes grammesdone

Page 19: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 19

∆οµή for– Πρόγραµµα forLoops2

#!/bin/bash

#Xwris lista timwn epe3ergazetai tis parametrous tou programmatosfor koko

do echo -n $koko; done

echo

#how to parse some arguments from $2 until the endfor j in ${*:2}

doecho -n $j;done

echo

#$2 to $4 - start at position 2 and use 3 argsfor j in ${*:2:3}

doecho -n $jdone

echo

mema@bowser> ./forLoops2 aa bb cc dd ee ff ggaabbccddeeffggbbccddeeffggbbccddmema@bowser>

Page 20: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 20

∆οµή while –Πρόγραµµα whileLoops

mema@bowser> ./whileLoops0 1 2 3 4 5 6 7 8 9 mema@bowser>

#!/bin/bashvar0=0LIMIT=10

while [ "$var0" -lt "$LIMIT" ]doecho -n "$var0 "var0=`expr $var0 + 1`

# var0=$(($var0+1)) also works.# var0=$((var0 + 1)) also works.# let "var0 += 1" also works.

doneechoexit 0

Page 21: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 21

Παράδειγµα– Πρόγραµµα breakCont

mema@bowser> ./breakCont

Numbers 1 through 20 (but not 3 and 11).1 2 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 1 2 mema@bowser>

#!/bin/bashLIMIT=19 # Upper limitechoecho "Numbers 1 through 20 (but not 3 and 11)."a=0while [ $a -le "$LIMIT" ]

doa=$(($a+1))#Agnohse ta 3, 11if [ "$a" -eq 3 ] || [ "$a" -eq 11 ]

then continue; # Move on to next iteration of loopfiecho -n "$a " # Den ekteleitai gia ta 3 and 11.done

echoa=0while [ "$a" -le "$LIMIT" ]

doa=$(($a+1))‏if [ "$a" -gt 2 ]

then break; # Skip entire rest of loop.fiecho -n "$a "done

echo

Page 22: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 22

Η εντολή “set -- $myvar”Πρόγραµµα setProg

mema@bowser> ./setProg ena dio tria tesseraInput parameters = 4Input parameters = 6onetwothreefourfivesixmema@bowser>

#!/bin/bash

echo Input parameters = $#myvar="one two three four five six"

#split based on blank chars#assign to input parameters!!set -- $myvar

echo Input parameters = $##Now prints 6

for kokodo

echo $kokodone

Page 23: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 23

Παράδειγµα – Πρόγραµµα revstrs

Πρόγραµµα που τυπώνει αντίστροφα τις συµβολοσειρέςεισόδου του, καθώς και το µήκος τους

mema@bowser> ./revstrs mitsos kitsos aap fitsos pitsos paaasostim --> 6 character(s).sostik --> 6 character(s).paa --> 3 character(s).sostif --> 6 character(s).sostip --> 6 character(s).aaap --> 4 character(s).mema@bowser>

#!/bin/bash# Usage: revstrs [string1 [string2 ...]]#for str

dostrlen=`expr length "$str"`# 8a arxhsoume ektypwsh apo to telos - Prepei na 3eroume mhkoschind=$strlenwhile test $chind -gt 0

doecho -n "`expr substr \"$str\" $chind 1`"chind=`expr $chind - 1`done

echo -n " --> "echo -n "$strlen"echo " character(s)."done

Page 24: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 24

Παράδειγµα – Πρόγραµµα listRegFiles

Ονόµατα κανονικών αρχείων εντός ενός καταλόγου

#!/bin/bash

OUTFILE=files.lst

dirName=${1-`pwd`} # To - dhlwnei default timh# An den dw8ei onoma katalogou apo xrhsth

echo "The name of the directory to work in: ${dirName}"

echo "Regular files in directory ${dirName}" > $OUTFILE

# -type f means regular filesfor file in "$( find $dirName -type f )"doecho "$file"

done | sort >> "$OUTFILE"# ^^^^^^^^^^^^^^^^^^# Anakateu8ynsh ta3inomhmenou stdout

mema@bowser> cd dirFoo/mema@bowser> lsbla1 bla2 files.lst kk1mema@bowser> ../listRegFiles /home/mema/courses/k24/bash-scripts/dirFoo/The name of the directory to work in: /home/mema/courses/k24/bash-scripts/dirFoo/mema@bowser> cat files.lstRegular files in directory /home/mema/courses/k24/bash-scripts/dirFoo/ /home/mema/courses/k24/bash-scripts/dirFoo/bla1/home/mema/courses/k24/bash-scripts/dirFoo/bla2/home/mema/courses/k24/bash-scripts/dirFoo/files.lst/home/mema/courses/k24/bash-scripts/dirFoo/kk1mema@bowser>

Page 25: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 25

Παράδειγµα – Πρόγραµµα shiftCommand

Επεξεργασία ορισµάτων προγράµµατος - Εντολή shift

#!/bin/bash# call with > 5 arguments

echo "All args are = $*"for str # prints OK even with change

doecho "The value of the iterator is: ${str} "var=$1shiftecho "var = $var and args = $*"done

mema@bowser> ./shiftCommand ena \> dio tria tesera pente exiAll args are = ena dio tria tesera pente exiThe value of the iterator is: enavar = ena and args = dio tria tesera pente exiThe value of the iterator is: diovar = dio and args = tria tesera pente exiThe value of the iterator is: triavar = tria and args = tesera pente exiThe value of the iterator is: teseravar = tesera and args = pente exiThe value of the iterator is: pentevar = pente and args = exiThe value of the iterator is: exivar = exi and args = mema@bowser>

Page 26: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 26

Παράδειγµα – Πρόγραµµα factorial

Υπολογίστε το παραγοντικό του αριθµού που περνιέται σαν όρισµα στοπρόγραµµα

#!/bin/bash# Usage: factorial number

if [ "$#" -ne 1 ] then echo "Just give one numeric argument"exit 1

fi

if [ "$1" -lt 0 ] then echo Please give positive numberexit 1

fi

fact=1for ((i = 1; i <= $1; i++)) ‏

dofact=`expr $fact \* $i`done

echo $fact

mema@bowser> ./factorial Just give one numeric argumentmema@bowser> ./factorial -2Please give positive numbermema@bowser> ./factorial 424mema@bowser> ./factorial 1487178291200mema@bowser> ./factorial 24expr: *: Numerical result out of rangeexpr: syntax errorexpr: syntax errorexpr: syntax error

mema@bowser>

Page 27: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 27

Παράδειγµα –Πρόγραµµα dirSize

Μέγιστο µέγεθος καταλόγου απόαυτούς που δίνονται ως ορίσµατα#!/bin/bash# Usage: dirSize dirName1 ... dirNameN#max=0; maxdir=$1; dirs=$*;for dir do

if [ ! -d $dir ]then echo "No directory with name $dir"

elsesize=`du -sk $dir | cut -f1` echo "Size of dir $dir is $size"if [ $size -ge $max ]

then max=$size ; maxdir=$dirfi # if size...

fi # if directorydoneecho "$maxdir $max"

mema@bowser> ./dirSize dirFoo ~/Size of dir dirFoo/ is 8Size of dir /home/mema/ is 19410624 /home/mema/ 19419624

Page 28: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 28

Παράδειγµα – Πρόγραµµα printContents

#!/bin/bash# Loads this script into an array and prints array to stdout

text=( $(cat "$0") )

echo ${text}echo " "; echo " "; echo “*****”;

for ((i=0; i <= ${#text[@]} - 1; i++))‏do

# ${#text[@]}# gives number of elements in the array# prints on a single line separated by "..."echo -n "${text[$i]}"echo -n " ... "

doneecho " "; echo " "; echo”*****”;

for i in `cat "${0}"`do

#each field of the script separated by "...."echo -n "${i}"echo -n " .... "

doneecho " "

•An array is a variable containing multiple values.•To initialize/assign elements to an array variable named text:text = (value1 value2 value3…)•${text[3]} is the value of element #3 in text array•${text} is same as ${text[0]} which is the value of element #0•If index number is @ or *, all members of an array are referenced. i.e., ${text[@]} or ${text[*]}

Page 29: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 29

Παράδειγµα – Πρόγραµµα printContents

mema@bowser> ./printContents#!/bin/bash

*****#!/bin/bash ... # ... Loads ... this ... script ... into ... an ... array. ... text=( ... $(cat ... "$0") ... ) ... echo ... ${text} ... echo ... " ... "; ... echo ... " ... "; ... echo ... "*****"; ... for ... ((i=0; ... i ... <= ... ${#text[@]} ... - ... 1; ... i++)) ... do ... # ... ${#text[@]} ... # ... gives ... number ... of ... elements ... in ... the ... array ... # ... prints ... on ... a ... single ... line ... each ... field ... separated ... by ... "..." ... echo ... ... "${text[$i]}" ... echo ... ... " ... ... ... " ... done ... echo ... " ... "; ... echo ... " ... "; ... echo ... "*****"; ... for ... i ... in ... `cat ... "${0}"` ... do ... #each ... field ... of ... the ... script ... separated ... by ... "...." ... echo ... ... "${i}" ... echo ... ... " ... .... ... " ... done ... echo ... " ... "; ... echo ... " ... "; ... echo ... "*****"; ...

*****#!/bin/bash .... # .... Loads .... this .... script .... into .... an .... array. .... text=( .... $(cat .... "$0") .... ) .... echo .... ${text} .... echo .... " .... "; .... echo .... " .... "; .... echo .... "*****"; .... for .... ((i=0; .... i .... <= .... ${#text[@]} .... - .... 1; .... i++)) .... do .... # .... ${#text[@]} .... # .... gives .... number .... of .... elements .... in .... the .... array .... # .... prints .... on .... a .... single .... line .... each .... field .... separated .... by .... "..." .... echo .... .... "${text[$i]}" .... echo .... .... " .... ... .... " .... done .... ech.... " .... "; .... echo .... " .... "; .... echo .... "*****"; .... for .... i .... in .... `cat .... "${0}"` ....do .... #each .... field .... of .... the .... script .... separated .... by .... "...." .... echo .... .... "${i}" .... echo .... .... " .... .... .... " .... done .... echo .... " .... "; .... echo .... " .... "; .... echo .... "*****"; ....

*****mema@bowser>

Page 30: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 30

Παράδειγµα – ΠρόγραµµαprintContents2∆ιάβασµα αρχείου γραµµή-γραµµή

#!/bin/bashexec < "$0" #Take input from this file

while read linedoecho $linedone

#IFS is an internal variable specifying #how bash separates fields, word boundaries#ALWAYS SAVE TO TEMP VARIABLE AND #RESET AFTERWARDS

OLDIFS="$IFS"; echo "--Old IFS value:" "$IFS"IFS=$'\n' #IFS= also worksecho "--New IFS value:" "$IFS"

for line in `cat "$0"` doecho "$line"done

IFS="$OLDIFS"exit 0

Default value of IFS is <space><tab><newline>With change, shell ignores lines with just spaces/tabs as it prints

Page 31: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 31

Παράδειγµα – ΠρόγραµµαprintContents2

ad@melbourne:~/K24/BASH-SCRIPTS/scripts$ ./printContents2 #!/bin/bashexec < "$0" #Take input from this file

while read linedoecho $linedone

#IFS is an internal variable specifying#how bash separates fields, word boundaries#ALWAYS SAVE TO TEMP VARIABLE AND#RESET AFTERWARDS

OLDIFS="$IFS"; echo "--Old IFS value:" "$IFS"

IFS=$'n' #IFS= also works

echo "--New IFS value:" "$IFS"

for line in `cat "$0"`doecho "$line"done

IFS="$OLDIFS"

exit 0--Old IFS value:

--New IFS value:

Page 32: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 32

Παράδειγµα – ΠρόγραµµαprintContents2

#!/bin/bashexec < "$0" #Take input from this filewhile read line

doecho $linedone

#IFS is an internal variable specifying #how bash separates fields, word boundaries#ALWAYS SAVE TO TEMP VARIABLE AND #RESET AFTERWARDSOLDIFS="$IFS"; echo "--Old IFS value:" "$IFS"IFS=$'\n' #IFS= also worksecho "--New IFS value:" "$IFS"for line in `cat "$0"`

doecho "$line"done

IFS="$OLDIFS"exit 0

Page 33: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 33

Παράδειγµα – Πρόγραµµα listAndCopy

Εύρεση *.h αρχείων σε κατάλογο. Αποθήκευση 3 πρώτων γραµµών τους σε αρχείο myout

#!/bin/sh#search for .h files in a specific directory#For each file in this dir, list first 3 lines in the file#into the file "myout"

FILE_LIST=`ls /usr/include/c++/4.2/gnu/java/lang/*.h`

touch myout; rm myout; touch myout;

for file in ${FILE_LIST}doecho FILE = ${file}

head -3 "${file}" >> myoutdone

Page 34: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 34

Παράδειγµα – Πρόγραµµα listAndCopy

Εύρεση *.h αρχείων σε κατάλογο. Αποθήκευση 3 πρώτων γραµµών τους σε αρχείο myout

mema@bowser> ./listAndCopyFILE = /usr/include/gnutls/compat4.hFILE = /usr/include/gnutls/compat8.hFILE = /usr/include/gnutls/extra.hFILE = /usr/include/gnutls/gnutls.hFILE = /usr/include/gnutls/openssl.hFILE = /usr/include/gnutls/x509.hmema@bowser> cat myout/* defines for compatibility with older versions.*/

#ifndef GNUTLS_COMPAT8_H# define GNUTLS_COMPAT8_H

/** Copyright (C) 2002 Nikos Mavroyanopoulos*/** Copyright (C) 2000,2001,2002,2003 Nikos Mavroyanopoulos*/** Copyright (c) 2002 Andrew McDonald <[email protected]>*/** Copyright (C) 2003 Nikos Mavroyanopoulos*mema@bowser>

Page 35: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 35

Παράδειγµα – Πρόγραµµα countword∆ιάβασµα αρχείου. Αφαίρεση πολλαπλώνσυνεχόµενων λέξεων. Εκτύπωση κάθε λέξης στηµορφή λέξη/# συνεχόµενες_εµφανίσεις

#!/bin/bashprev=""; cons=1;

for str in `cat ${1}` doif [ "${str}" != "$prev" ]

thenif [ ! -z $prev ] then

echo "${prev}/${cons} "fiprev=${str}cons=1

elselet "cons = cons + 1"

fidone

if [ ! -z prev ]thenecho "${prev}/${cons}"

fi

Page 36: Topic 2: Bash Shell Programmingcgi.di.uoa.gr/.../k24/lectures/old/topic2-bashShellProgramming.pdf · Topic 2: Bash Shell Programming* * ... Inherits many features from C & Korn shells

K24: Προγραµµατισµός Συστήµατος 36

Παράδειγµα – Πρόγραµµα countword

mema@bowser> more test-filethis is is a test file

another example example example of a test test testtest file filemema@bowser> ./countword test-file this/1 is/2 a/1 test/1 file/1 another/1 example/3 of/1 a/1 test/4 file/2mema@bowser>