bashshell-130121051123-phpapp01.ppt

download bashshell-130121051123-phpapp01.ppt

of 53

Transcript of bashshell-130121051123-phpapp01.ppt

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    1/53

    Bash Shell

    Lecturer: Prof. Andrzej (AJ) BieszczadEmail: [email protected]

    Phone: 818!""#$%#

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    2/53

    Bash Shell

    The shell of Linux

    &Linu' has a ariet of different shells:*Bourne shell (sh)+ , shell (csh)+ -orn shell (sh)+ /, shell (tcsh)+Bourne A0ain shell (ash).

    &,ertainl the most 2o2ular shell is 3ash4. Bash is an sh

    com2atileshell that incor2orates useful features from the-orn shell (sh) and , shell (csh).

    &5t is intended to conformto the 5EEE P675 P199.;

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    3/53

    Bash Shell

    Programming or Scripting ?

    & ash is not onl an e'cellent command line shell+ ut a scri2tin0 lan0ua0einitself. 7hell scri2tin0 allo=s us to use the shell>s ailities and to automate a lot oftassthat =ould other=ise re?uire a lot of commands.

    & ifference et=een 2ro0rammin0 and scri2tin0 lan0ua0es:

    * Pro0rammin0 lan0ua0esare 0enerall a lot more 2o=erful and a lot faster thanscri2tin0 lan0ua0es. Pro0rammin0 lan0ua0es 0enerall start from source code and arecom2iled into an e'ecutale. /his e'ecutale is not easil 2ortedinto different o2eratin0sstems.

    *A scri2tin0 lan0ua0ealso starts from source code+ ut is not com2iled into ane'ecutale. ather+ an inter2reterreads the instructions in the source file and e'ecuteseach instruction. 5nter2reted 2ro0rams are 0enerall slo=er than com2iled 2ro0rams.

    /he main adanta0e is that ou can easil 2ortthe source file to an o2eratin0 sstem.ash is a scri2tin0 lan0ua0e. 6ther e'am2les of scri2tin0 lan0ua0es are Perl+ Lis2+ and/cl.

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    4/53

    Bash Shell

    The first bash program

    &/here are t=o major te't editors in Linu':* i+ emacs (or 'emacs).

    & 7o fire u2 a te't editor for e'am2le:

    C i D

    and t2e the follo=in0 inside it:

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    5/53

    Bash Shell

    The second bash program

    &He =rite a 2ro0ram that co2ies all files into a director+ and then deletes thedirector alon0 =ith its contents. /his can e done =ith the follo=in0 commands:

    C mdir trashC c2 I trashC rm rf trash

    C mdir trash

    & 5nstead of hain0 to t2e all that interactiel on the shell+ =rite a shell 2ro0raminstead:

    C cat trash.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    6/53

    Bash Shell

    Variables

    &He can use arialesas in an 2ro0rammin0 lan0ua0es. /heir alues areal=as stored as strin0s+ ut there are mathematical o2erators in the shelllan0ua0e that =ill conert ariales to numers for calculations.

    & He hae no need to declare a ariale+ just assi0nin0 a alue to its reference =illcreate it.

    & E'am2le

    #!/bin/bash

    STR=Hello World!

    echo $STR

    & Line ; creates a ariale called 7/ and assi0ns the strin0 Gello HorldF to it./hen the alue of this ariale is retrieed 2uttin0 the >C> in at the e0innin0.

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    7/53

    Bash Shell

    Warning !

    &/he shell 2ro0rammin0 lan0ua0e does not t2ecastits ariales. /his meansthat a ariale can hold numer data or character data.

    countK9countK7unda

    & 7=itchin0 the /PE of a ariale can lead to confusion for the =riter of the scri2tor someone trin0 to modif it+ so it is recommended to use a ariale for onl asin0le /PE of datain a scri2t.

    & Mis the ash esca2e character and it 2reseres the literal alue of the ne'tcharacter that follo=s.

    Cls MIls: I: No such file or director

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    8/53

    Bash Shell

    Single and Double Quote

    &Hhen assi0nin0 character data containin0 s2aces or s2ecial characters+ the datamust e enclosed in either sin0le or doule ?uotes.

    & Osin0 doule ?uotesto sho= a strin0 of characters =ill allo= an ariales in the?uotes to e resoled

    CarK3test strin04Cne=arK3alue of ar is Car4Cecho Cne=aralue of ar is test strin0

    & Osin0 sin0le ?uotesto sho= a strin0 of characters =ill not allo= arialeresolution

    CarKQtest strin0QCne=arKQalue of ar is CarQCecho Cne=aralue of ar is Car

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    9/53

    Bash Shell

    The export command

    &/he e'2ort command 2uts a ariale into the enironment so it =ill e accessileto child 2rocesses. Ror instance:

    C 'KhelloC ash un a child shell.C echo C' Nothin0 in '.

    C e'it eturn to 2arent.C e'2ort 'C ashC echo C'hello 5t>s there.

    & 5f the child modifies '+ it =ill not modif the 2arentQs ori0inal alue. erif this chan0in0 ' in the follo=in0 =a:

    C 'KciaoC e'itC echo C'hello

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    10/53

    Bash Shell

    nironmental Variables

    & /here are t=o t2es of ariales:

    & Local ariales& Enironmental ariales

    & Enironmental ariales are set the sstem and can usuall e found usin0 the encommand. Enironmental ariales hold s2ecial alues. Ror instance:

    C echo C7GELL

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    11/53

    Bash Shell

    nironmental Variables

    & G6UE: /he default ar0ument (home director) for cd.& PA/G: /he search 2ath for commands. 5t is a colonse2arated list of directories that are

    searched =hen ou t2e a command.

    & Osuall+ =e t2e in the commands in the follo=in0 =a:

    C .

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    12/53

    Bash Shell

    nironemnt Variables

    & L6VNAUE: contains the user name& G67/NAUE: contains the com2uter name.

    & P71: se?uence of characters sho=n efore the 2rom2t

    Mt hourMd dateM= current director

    MH last 2art of the current directorMu user nameMC 2rom2t character

    E'am2le:

    Wuserid@homelinu' useridXC P71KYhi Mu IQ

    hi useridI T

    E'ercise KKZesi0n our o=n ne= 2rom2t. 7ho= me =hen ou are ha22 =ith it.

    & AN6U: random numer 0enerator& 7E,6N7: seconds from the e0innin0 of the e'ecution

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    13/53

    Bash Shell

    "ead command

    & /he read command allo=s ou to 2rom2t for in2ut and store it in a ariale.

    & E'am2le:

    F to remoe it+ >n> to chan0e our mind ... 4rm i Cfileecho /hat =as 6O decisionF4

    & Line ; 2rom2ts for a strin0 that is read in line . Line # uses the interactie

    remoe (rm i) to as the user for confirmation.

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    14/53

    Bash Shell

    #ommand Substitution

    & /he ac?uote3[4 is different from the sin0le ?uote3\4. 5t is used for command sustitution:[command[

    C L57/K[ls[C echo CL57/hello.sh read.sh

    C P71K3[2=d[Z4

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    15/53

    Bash Shell

    $rithmetic aluation

    & /he letstatement can e used to do mathematical functions:

    C let K19];I"C echo C;#C let K];I#

    C echo C;

    &An arithmetic e'2ressioncan e ealuated CWe'2ressionXor C((e'2ression))

    C echo 3C((1;];9))4

    1#C AL6EKCW1;];9XC echo 3CW1;ICAL6EX41"%8$

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    16/53

    Bash Shell

    $rithmetic aluation

    &Aailale o2erators: ]+ +

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    17/53

    Bash Shell

    #onditional Statements

    & ,onditionalslet us decide =hether to 2erform an action or not+ this decision istaen ealuatin0 an e'2ression. /he most asic form is:

    if W e'2ression Xthen

    statements

    elif W e'2ression Xthenstatements

    elsestatements

    fi

    & the elif(else if) and elsesections are o2tional

    & Put s2aces after W andefore X+ andaround the o2erators ando2erands.

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    18/53

    Bash Shell

    xpressions

    &An e'2ressioncan e: 7trin0 com2arison+ Numeric com2arison+ Rile o2eratorsand Lo0ical o2eratorsand it is re2resented We'2ressionX:

    & 7trin0 ,om2arisons:

    K com2are if t=o strin0s are e?ual

    FK com2are if t=o strin0s are not e?ualn ealuate if strin0 len0th is 0reater than zeroz ealuate if strin0 len0th is e?ual to zero

    & E'am2les:

    W s1 K s; X (true if s1 same as s;+ else false)W s1 FK s; X (true if s1 not same as s;+ else false)W s1 X (true if s1 is not em2t+ else false)W n s1 X (true if s1 has a len0th 0reater then 9+ else false)W z s; X (true if s; has a len0th of 9+ other=ise false)

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    19/53

    Bash Shell

    xpressions

    & Numer ,om2arisons:

    e? com2are if t=o numers are e?ual0e com2are if one numer is 0reater than or e?ualto a numerle com2are if one numer is less than or e?ualto a numerne com2are if t=o numers are not e?ual

    0t com2are if one numer is 0reaterthan another numerlt com2are if one numer is lessthan another numer

    & E'am2les:

    W n1 e? n; X (true if n1 same as n;+ else false)

    W n1 0e n; X (true if n10reater then or e?ual to n;+ else false)W n1 le n; X (true if n1 less then or e?ual to n;+ else false)W n1 ne n; X (true if n1 is not same as n;+ else false)W n1 0t n; X (true if n1 0reater then n;+ else false)W n1 lt n; X (true if n1 less then n;+ else false)

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    20/53

    Bash Shell

    xamples

    C cat user.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    21/53

    Bash Shell

    xpressions

    & Riles o2erators:

    d chec if 2ath 0ien is a directorf chec if 2ath 0ien is a filee chec if file name e'istsr chec if read 2ermissionis set for file or directors chec if a file has a len0th 0reater than 9

    = chec if =rite 2ermissionis set for a file or director' chec if e'ecute 2ermissionis set for a file or director

    & E'am2les:

    W d fname X (true if fname is a director+ other=ise false)

    W f fname X (true if fname is a file+ other=ise false)W e fname X (true if fname e'ists+ other=ise false)W s fname X (true if fname len0th is 0reater then 9+ else false)W r fname X (true if fname has the read 2ermission+ else false)W = fname X (true if fname has the =rite 2ermission+ else false)W ' fname X (true if fname has the e'ecute 2ermission+ else false)

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    22/53

    Bash Shell

    xample

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    23/53

    Bash Shell

    xpressions

    & Lo0ical o2erators:

    F ne0ate (N6/) a lo0ical e'2ressiona lo0icallANt=o lo0ical e'2ressionso lo0icall 6t=o lo0ical e'2ressions

    E'am2le:

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    24/53

    Bash Shell

    xpressions

    & Lo0ical o2erators:

    DD lo0icallANt=o lo0ical e'2ressionsbblo0icall 6t=o lo0ical e'2ressions

    E'am2le:

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    25/53

    Bash Shell

    xample

    C cat iftrue.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    26/53

    Bash Shell

    Shell Parameters

    & Positional 2arametersare assi0ned from the shellQs ar0ument =hen it is inoed.Positional 2arameter 3N4 ma e referenced as 3CN4+ or as 3CN4 =hen 3N4consists of a sin0le di0it.

    & 72ecial 2arameters

    C is the numer of 2arameters2assed

    C9 returns the name of the shell scri2trunnin0 as =ell as itslocation in the file sstem

    CI 0ies a sin0le =ord containin0 all the 2arameters2assedto the scri2t

    C@ 0ies an arra of =ords containin0 all the 2arameters2assed to the scri2t

    C cat s2arameters.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    27/53

    Bash Shell

    Trash

    C cat trash.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    28/53

    Bash Shell

    #ase Statement

    & Osed to e'ecute statements ased on s2ecific alues. 6ften used in 2lace of anif statement if there are a lar0e numer of conditions.

    & alue used can e an e'2ression& each set of statements must e ended a 2air of semicolons& a I)is used to acce2t an alue not matched =ith list of alues

    case Car inal1)

    statementsal;)

    statements

    I) statementsesac

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    29/53

    Bash Shell

    xample %case&sh'

    C cat case.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    30/53

    Bash Shell

    (teration Statements

    & /he for structureis used =hen ou are loo2in0 throu0h a ran0e of ariales.

    for ar in listdo statementsdone

    & statements are e'ecuted =ith ar set to each alue in the list.

    & E'am2le

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    31/53

    Bash Shell

    (teration Statements

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    32/53

    Bash Shell

    xample %old&sh'

    C cat old.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    33/53

    Bash Shell

    xample %args&sh'

    C cat ar0s.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    34/53

    Bash Shell

    )sing $rra*s +ith Loops

    & 5n the ash shell+ =e ma use arras. /he sim2lest =a to create one is usin0 one of the t=o

    suscri2ts:

    2etW9XKdo02etW1XKcat2etW;XKfish2etK(do0 cat fish)

    & He ma hae u2 to 19;# elements. /o e'tracta alue+ t2e CarranameWiX

    C echo C2etW9Xdo0

    & /o e'tract all the elements+ use an asteris as:

    echo CarranameWIX

    & He can comine arras =ith loo2susin0 a for loo2:

    for ' in CarranameWIXdo...done

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    35/53

    Bash Shell

    $ #,li-e for loop

    &An alternatieform of the forstructure is

    for (( EP1 EP; EP ))do statementsdone

    & Rirst+ the arithmetic e'2ression EP1 is ealuated. EP; is then ealuatedre2eatedl until it ealuates to 9. Each time EP; is ealuates to a nonzeroalue+ statements are e'ecuted and EP is ealuated.

    C cat for;.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    36/53

    Bash Shell

    Debugging

    & Bash 2roides t=o o2tions =hich =ill 0ie useful information for deu00in0

    ': dis2las each line of the scri2t =ith ariale sustitution and efore e'ecution: dis2las each line of the scri2t as t2ed efore e'ecution

    & Osa0e:

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    37/53

    Bash Shell

    Debugging

    C for.sh

    ] echo *n YEnter a numer: QEnter a numer: ] read '] let sumK9] (( iK9 ))] (( 9K ))] let Ysum K 9 ] 9Q

    ] (( iK9]1 ))] (( 1K ))] let Ysum K 9 ] 1Q] (( iK1]1 ))] (( ;K ))] let Ysum K 1 ] ;Q] (( iK;]1 ))

    ] (( K ))] let Ysum K ] Q] (( iK]1 ))] (( #K ))] echo Ythe sum of the first numers is: !Qthe sum of the first numers is: !

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    38/53

    Bash Shell

    While Statements

    & /he =hile structure is a loo2in0 structure. Osed to e'ecute a set of commands

    =hile a s2ecified condition is true. /he loo2 terminates as soon as the conditionecomes false. 5f condition neer ecomes false+ loo2 =ill neer e'it.

    =hile e'2ressiondo

    statementsdone

    C cat =hile.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    39/53

    Bash Shell

    .enu

    C cat menu.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    40/53

    Bash Shell

    /ind a Pattern and dit

    C cat 0re2edit.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    41/53

    Bash Shell

    #ontinue Statements

    & /he continuecommand causes a jum2 to the ne't iteration of the loo2+ si22in0

    all the remainin0 commands in that 2articular loo2 ccle.

    C cat continue.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    42/53

    Bash Shell

    Brea- Statements

    & /he reacommand terminates the loo2(reas out of it).

    C cat rea.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    43/53

    Bash Shell

    )ntil Statements

    & /he untilstructure is er similar to the =hile structure. /he until structure loo2s

    until the condition is true. 7o asicall it is 3until this condition is true+ do this4.until We'2ressionXdo

    statementsdone

    C cat countdo=n.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    44/53

    Bash Shell

    .anipulating Strings

    & Bash su22orts a numer of strin0 mani2ulation o2erations.

    Cstrin00ies the strin0 len0thCstrin0:2ositione'tracts sustrin0from Cstrin0 at C2ositionCstrin0:2osition:len0the'tracts Clen0th characters of sustrin0from Cstrin0 atC2osition

    & E'am2le

    C stK91;#%!"8$C echo Cst19

    C echo Cst:!!"8$C echo Cst:!:;!"

    B h Sh ll

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    45/53

    Bash Shell

    Parameter Substitution

    & Uani2ulatin0 and

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    46/53

    Bash Shell

    Parameter Substitution

    C2arameter`ms0+ if 2arameter set+ use it+ else 2rint ms0

    C alueKCtotal`Qtotal is not setQtotal: total is not set

    C totalK19C alueKCtotal`Qtotal is not setQC echo Calue

    19

    E'am2le

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    47/53

    Bash Shell

    /unctions

    & Runctions mae scri2ts easier to maintain. Basicall it reas u2 the 2ro0ram

    into smaller 2ieces. A function 2erforms an action defined ou+ and it canreturn a alue if ou =ish.

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    48/53

    Bash Shell

    /unctions

    C cat function.sh

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    49/53

    Bash Shell

    xample0 Pic-ing a random card from a dec-

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    50/53

    Bash Shell

    xample0 #hanges all filenames to lo+ercase

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    51/53

    Bash Shell

    xample0 #ompare t+o files +ith a script

    F

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    52/53

    Bash Shell

    xample0 Suite dra+ing statisticsC cat cardstats.shF

  • 7/26/2019 bashshell-130121051123-phpapp01.ppt

    53/53

    Bash Shell

    #hallenge1Pro2ect0 collect

    & Hrite a utilit to collect 3=ellno=n4 files into conenient director holders.

    collect directorZI

    & /he utilit should collectall e'ecutales+ liraries+ sources and includes from eachdirector 0ien on the command line or entered the user(if no ar0uments =ere 2assed)into se2arate directories. B default+ the allocation is as follo=s:* e'ecutales0o to S