bash scripting tutorial

Upload: nagaraj

Post on 28-Feb-2018

247 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 Bash Scripting Tutorial

    1/22

    Bash scripting Tutorial

    o Hello World Bash Shell Script

    o Simple Backup bash shell script

    o Variables

    Global vs. Local variables

    o Passing arguments to the bash script

    o Executing shell commands ith bash

    o !eading "ser #nput

    o Bash $rap %ommand

    o &rra's

    (eclare simple bash arra'

    !ead )ile into bash arra'

    o Bash i) * else * )i statements

    Simple Bash i)*else statement

    +ested i)*else

    o Bash %omparisons

    &rithmetic %omparisons

    String %omparisons

    o Bash ,ile $esting

    o Loops

    Bash )or loop

    Bash hile loop

    1

    https://linuxconfig.org/bash-scripting-tutorial#h1-hello-world-bash-shell-scripthttps://linuxconfig.org/bash-scripting-tutorial#h2-simple-backup-bash-shell-scripthttps://linuxconfig.org/bash-scripting-tutorial#h3-variableshttps://linuxconfig.org/bash-scripting-tutorial#h3-1-global-vs-local-variableshttps://linuxconfig.org/bash-scripting-tutorial#h4-passing-arguments-to-the-bash-scripthttps://linuxconfig.org/bash-scripting-tutorial#h5-executing-shell-commands-with-bashhttps://linuxconfig.org/bash-scripting-tutorial#h6-reading-user-inputhttps://linuxconfig.org/bash-scripting-tutorial#h7-bash-trap-commandhttps://linuxconfig.org/bash-scripting-tutorial#h8-arrayshttps://linuxconfig.org/bash-scripting-tutorial#h8-1-declare-simple-bash-arrayhttps://linuxconfig.org/bash-scripting-tutorial#h8-2-read-file-into-bash-arrayhttps://linuxconfig.org/bash-scripting-tutorial#h9-bash-if-else-fi-statementshttps://linuxconfig.org/bash-scripting-tutorial#h9-1-simple-bash-if-else-statementhttps://linuxconfig.org/bash-scripting-tutorial#h9-2-nested-if-elsehttps://linuxconfig.org/bash-scripting-tutorial#h10-bash-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h10-1-arithmetic-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h10-2-string-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h11-bash-file-testinghttps://linuxconfig.org/bash-scripting-tutorial#h12-loopshttps://linuxconfig.org/bash-scripting-tutorial#h12-1-bash-for-loophttps://linuxconfig.org/bash-scripting-tutorial#h12-2-bash-while-loophttps://linuxconfig.org/bash-scripting-tutorial#h2-simple-backup-bash-shell-scripthttps://linuxconfig.org/bash-scripting-tutorial#h3-variableshttps://linuxconfig.org/bash-scripting-tutorial#h3-1-global-vs-local-variableshttps://linuxconfig.org/bash-scripting-tutorial#h4-passing-arguments-to-the-bash-scripthttps://linuxconfig.org/bash-scripting-tutorial#h5-executing-shell-commands-with-bashhttps://linuxconfig.org/bash-scripting-tutorial#h6-reading-user-inputhttps://linuxconfig.org/bash-scripting-tutorial#h7-bash-trap-commandhttps://linuxconfig.org/bash-scripting-tutorial#h8-arrayshttps://linuxconfig.org/bash-scripting-tutorial#h8-1-declare-simple-bash-arrayhttps://linuxconfig.org/bash-scripting-tutorial#h8-2-read-file-into-bash-arrayhttps://linuxconfig.org/bash-scripting-tutorial#h9-bash-if-else-fi-statementshttps://linuxconfig.org/bash-scripting-tutorial#h9-1-simple-bash-if-else-statementhttps://linuxconfig.org/bash-scripting-tutorial#h9-2-nested-if-elsehttps://linuxconfig.org/bash-scripting-tutorial#h10-bash-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h10-1-arithmetic-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h10-2-string-comparisonshttps://linuxconfig.org/bash-scripting-tutorial#h11-bash-file-testinghttps://linuxconfig.org/bash-scripting-tutorial#h12-loopshttps://linuxconfig.org/bash-scripting-tutorial#h12-1-bash-for-loophttps://linuxconfig.org/bash-scripting-tutorial#h12-2-bash-while-loophttps://linuxconfig.org/bash-scripting-tutorial#h1-hello-world-bash-shell-script
  • 7/25/2019 Bash Scripting Tutorial

    2/22

    Bash until loop

    %ontrol bash loop ith

    o Bash ,unctions

    o Bash Select

    o %ase statement conditional

    o Bash -uotes and -uotations

    Escaping eta characters

    Single -uotes

    (ouble /uotes

    Bash -uoting ith &+S#0% st'le

    o &rithmetic 1perations

    Bash &ddition %alculator Example

    Bash &rithmetics

    !ound )loating point number

    Bash )loating point calculations

    o !edirections

    S$(1"$ )rom bash script to S$(E!!

    S$(E!! )rom bash script to S$(1"$

    stdout to screen

    stdout to )ile

    stderr to )ile

    stdout to stderr

    stderr to stdout

    2

    https://linuxconfig.org/bash-scripting-tutorial#h12-3-bash-until-loophttps://linuxconfig.org/bash-scripting-tutorial#h12-4-control-bash-loop-withhttps://linuxconfig.org/bash-scripting-tutorial#h13-bash-functionshttps://linuxconfig.org/bash-scripting-tutorial#h14-bash-selecthttps://linuxconfig.org/bash-scripting-tutorial#h15-case-statement-conditionalhttps://linuxconfig.org/bash-scripting-tutorial#h16-bash-quotes-and-quotationshttps://linuxconfig.org/bash-scripting-tutorial#h16-1-escaping-meta-charactershttps://linuxconfig.org/bash-scripting-tutorial#h16-2-single-quoteshttps://linuxconfig.org/bash-scripting-tutorial#h16-3-double-quoteshttps://linuxconfig.org/bash-scripting-tutorial#h16-4-bash-quoting-with-ansi-c-stylehttps://linuxconfig.org/bash-scripting-tutorial#h17-arithmetic-operationshttps://linuxconfig.org/bash-scripting-tutorial#h17-1-bash-addition-calculator-examplehttps://linuxconfig.org/bash-scripting-tutorial#h17-2-bash-arithmeticshttps://linuxconfig.org/bash-scripting-tutorial#h17-3-round-floating-point-numberhttps://linuxconfig.org/bash-scripting-tutorial#h17-4-bash-floating-point-calculationshttps://linuxconfig.org/bash-scripting-tutorial#h18-redirectionshttps://linuxconfig.org/bash-scripting-tutorial#h18-1-stdout-from-bash-script-to-stderrhttps://linuxconfig.org/bash-scripting-tutorial#h18-2-stderr-from-bash-script-to-stdouthttps://linuxconfig.org/bash-scripting-tutorial#h18-3-stdout-to-screenhttps://linuxconfig.org/bash-scripting-tutorial#h18-4-stdout-to-filehttps://linuxconfig.org/bash-scripting-tutorial#h18-5-stderr-to-filehttps://linuxconfig.org/bash-scripting-tutorial#h18-6-stdout-to-stderrhttps://linuxconfig.org/bash-scripting-tutorial#h18-7-stderr-to-stdouthttps://linuxconfig.org/bash-scripting-tutorial#h12-3-bash-until-loophttps://linuxconfig.org/bash-scripting-tutorial#h12-4-control-bash-loop-withhttps://linuxconfig.org/bash-scripting-tutorial#h13-bash-functionshttps://linuxconfig.org/bash-scripting-tutorial#h14-bash-selecthttps://linuxconfig.org/bash-scripting-tutorial#h15-case-statement-conditionalhttps://linuxconfig.org/bash-scripting-tutorial#h16-bash-quotes-and-quotationshttps://linuxconfig.org/bash-scripting-tutorial#h16-1-escaping-meta-charactershttps://linuxconfig.org/bash-scripting-tutorial#h16-2-single-quoteshttps://linuxconfig.org/bash-scripting-tutorial#h16-3-double-quoteshttps://linuxconfig.org/bash-scripting-tutorial#h16-4-bash-quoting-with-ansi-c-stylehttps://linuxconfig.org/bash-scripting-tutorial#h17-arithmetic-operationshttps://linuxconfig.org/bash-scripting-tutorial#h17-1-bash-addition-calculator-examplehttps://linuxconfig.org/bash-scripting-tutorial#h17-2-bash-arithmeticshttps://linuxconfig.org/bash-scripting-tutorial#h17-3-round-floating-point-numberhttps://linuxconfig.org/bash-scripting-tutorial#h17-4-bash-floating-point-calculationshttps://linuxconfig.org/bash-scripting-tutorial#h18-redirectionshttps://linuxconfig.org/bash-scripting-tutorial#h18-1-stdout-from-bash-script-to-stderrhttps://linuxconfig.org/bash-scripting-tutorial#h18-2-stderr-from-bash-script-to-stdouthttps://linuxconfig.org/bash-scripting-tutorial#h18-3-stdout-to-screenhttps://linuxconfig.org/bash-scripting-tutorial#h18-4-stdout-to-filehttps://linuxconfig.org/bash-scripting-tutorial#h18-5-stderr-to-filehttps://linuxconfig.org/bash-scripting-tutorial#h18-6-stdout-to-stderrhttps://linuxconfig.org/bash-scripting-tutorial#h18-7-stderr-to-stdout
  • 7/25/2019 Bash Scripting Tutorial

    3/22

    stderr and stdout to )ile

    $his bash script tutorial assumes no previous knoledge o) bash scripting.&s 'ou ill soondiscover in this -uick comprehensive bash scripting guide2 learning the bash shell scripting isver' eas' task. Hoever2 i) 'ou do not )ind an anser to 'our -uestions b' reading this bashtutorial or 'ou need extra help2 )eel )ree to ask us on our neLinux ,orum.We ill be more

    than happ' to help 'ou ith 'our bash -uestions there.

    Lets begin this bash scripting tutorial ith a simple 3Hello World3 script. Let4s start ithLearning the bash Shell5 "nix Shell Programming

    1. Hello World Bash Shell Script

    ,irst 'ou need to )ind out here is 'our bash interpreter located. Enter the )olloing into 'ourcommand line5

    $ which bash

    1pen up 'ou )avorite text editor and a create )ile called hello6orld.sh. #nsert the )olloing linesto a )ile5

    +1$E5Ever' bash shell script in this tutorial starts ith shebang:"#!"hich is not read as acomment. ,irst line is also a place here 'ou put 'our interpreter hich is in this case5 *bin*bash.

    Here is our )irst bash shell script example5

    #!/bin/bash# declare STRING variableSTRING="Hello World"#print variable on a screenecho $STRING

    +avigate to a director' here 'our hello6orld.sh is located and make the )ile executable5

    $ chod helloworldsh

    +o 'ou are read' to execute 'our )irst bash script5

    /helloworldsh

    3

    https://linuxconfig.org/bash-scripting-tutorial#h18-8-stderr-and-stdout-to-filehttp://forum.linuxcareer.com/http://forum.linuxcareer.com/http://forum.linuxcareer.com/https://linuxconfig.org/bash-scripting-tutorial#h18-8-stderr-and-stdout-to-filehttp://forum.linuxcareer.com/
  • 7/25/2019 Bash Scripting Tutorial

    4/22

    2. Simple Backup bash shell script

    #!/bin/bashtar %c&' (hoedirector(tar)& /hoe/lin*con'i)

    . ariables

    #n this example e declare simple bash variable and print it on the screen 7 stdout 8 ith echo

    command.

    #!/bin/bashSTRING="H+,,- W-R,.!!!"echo $STRING

    9our backup script and variables5

    #!/bin/bash-=(hoedirector($0date 1211d3tar)&tar %c&' $- /hoe/lin*con'i)

    .1. lobal s. $ocal ariables

    #!/bin/bash

    #.e'ine bash )lobal variable#This variable is )lobal and can be *sed an(where in this bash script45R=")lobal variable"'*nction bash 6#.e'ine bash local variable#This variable is local to bash '*nction onl(local 45R="local variable"echo $45R7

    4

  • 7/25/2019 Bash Scripting Tutorial

    5/22

    echo $45Rbash# Note the bash )lobal variable did not chan)e# "local" is bash reserved wordecho $45R

    %. &assing arguments to the bash script

    #!/bin/bash# *se prede'ined variables to access passed ar)*ents#echo ar)*ents to the shellecho $8 $9 $: ; %< echo $8 $9 $:;

    # We can also store ar)*ents 'ro bash coand line in special arra(

    ar)s=0"$"3#echo ar)*ents to the shellecho $6ar)s>?@7 $6ar)s>8@7 $6ar)s>9@7 ; %< ar)s=0"$"3A echo $6ar)s>?@7 $6ar)s>8@7 $6ar)s>9@7;

    #*se $ to print o*t all ar)*ents at onceecho $ ; %< echo $;

    # *se $# variable to print o*t# n*ber o' ar)*ents passed to the bash scriptecho N*ber o' ar)*ents passedB $# ; %< echo N*ber o' ar)*ents passedB $#;/ar)*entssh Cash Scriptin) T*torial

    '. ()ecuting shell commands *ith bash

    #!/bin/bash# *se bacDticDs " E E " to eec*te shell coandecho E*nae %oE

    # eec*tin) bash coand witho*t bacDticDsecho *nae %o

    5

  • 7/25/2019 Bash Scripting Tutorial

    6/22

    +. ,eading -ser nput

    #!/bin/bashecho %e "HiF please t(pe the wordB c "read wordecho "The word (o* entered isB $word"echo %e "an (o* please enter two words "read word8 word9echo "Here is (o*r inp*tB "$word8" "$word9""echo %e "How do (o* 'eel abo*t bash scriptin) "# read coand now stores a repl( into the de'a*lt b*ild%in variable $R+J,2readecho "2o* said $R+J,2F I; )lad to hear that! "echo %e "What are (o*r 'avorite colo*rs "

    # %a aDes read coand to read into an arra(read %a colo*rsecho "K( 'avorite colo*rs are also $6colo*rs>?@7F $6colo*rs>8@7 and $6colo*rs>9@7B%3"

    /. Bash Trap 0ommand

    #!/bin/bash# bash trap coandtrap bashtrap INT# bash clear screen coandclearA

    # bash trap '*nction is eec*ted whenTR,% is pressedB# bash prints essa)e =< +ec*tin) bashtrap s*br*tine !bashtrap036 echo "TR, .etected !eec*tin)bash trap !"7# 'or loop 'ro 8/8? to 8?/8?

    6

  • 7/25/2019 Bash Scripting Tutorial

    7/22

    'or a in EseL 8 8?EA do echo "$a/8? to +it"

    sleep 8Adoneecho "+it Cash Trap +aple!!!"

    . rra3s.1. 4eclare simple bash arra3

    #!/bin/bash#.eclare arra( with M eleents5RR52=0 ;.ebian ,in*; ;Redhat ,in*; b*nt* ,in* 3# )et n*ber o' eleents in the arra(+,+K+NTS=$6#5RR52>@7

    # echo each eleent in arra(# 'or loop'or 00 i=?AiO$+,+K+NTSAi33A do echo $65RR52>$6i7@7done

    .2. ,ead 5ile into bash arra3

    #!/bin/bash# .eclare arra(declare %a 5RR52# ,inD 'iledescriptor 8? with stdineec 8?OP?# stdin replaced with a 'ile s*pplied as a 'irst ar)*enteec O $8let co*nt=?

    while read ,IN+A do

    5RR52>$co*nt@=$,IN+ 00co*nt33done

    echo N*ber o' eleentsB $6#5RR52>@7# echo arra(;s contentecho $65RR52>@7# restore stdin 'ro 'iledescriptor 8?# and close 'iledescriptor 8?eec ?OP8? 8?OP%

    Bash script e)ecution *ith an output:

    7

  • 7/25/2019 Bash Scripting Tutorial

    8/22

    lin*con'i)or) $ cat bashttCashScriptin)T*torialG*idelin*con'i)or) $ /bash%scriptsh bashttN*ber o' eleentsB MCash Scriptin) T*torial G*ide

    lin*con'i)or) $

    6. Bash i5 7 else 7 5i statements

    6.1. Simple Bash i57else statement

    Please note the spacing inside the : and ; brackets< Without the spaces2 it on4t ork %d $director( @A then

    echo ".irector( eists"else

    echo ".irector( does not eists"'i

    6.2. 8ested i57else

    #!/bin/bash# .eclare variable choice and assi)n val*e Mchoice=M# Jrint to stdo*techo "8 Cash"echo "9 Scriptin)"echo ": T*torial"echo %n "Jlease choose a word >8F9 or :@ "

    # ,oop while the variable choice is eL*al M# bash while loopwhile > $choice %eL M @A do# read *ser inp*tread choice# bash nested i'/elsei' > $choice %eL 8 @ A then

    echo "2o* have chosen wordB Cash"

    8

  • 7/25/2019 Bash Scripting Tutorial

    9/22

    else

    i' > $choice %eL 9 @ A then echo "2o* have chosen wordB Scriptin)" else

    i' > $choice %eL : @ A then

    echo "2o* have chosen wordB T*torial" else echo "Jlease aDe a choice between 8%: !" echo "8 Cash" echo "9 Scriptin)" echo ": T*torial" echo %n "Jlease choose a word >8F9 or :@ " choice=M 'i

    'i'idone

    19. Bash 0omparisons

    19.1. rithmetic 0omparisons

    0lt =

    0gt >

    0le =?

    0ge >?

    0e- ??

    0ne

  • 7/25/2019 Bash Scripting Tutorial

    10/22

    echo "4al*es are N-T eL*al"'i

    #!/bin/bash

    # declare inte)ersNK8=9NK9=8i' > $NK8 %eL $NK9 @A then

    echo "Coth 4al*es are eL*al"else

    echo "4al*es are N-T eL*al"'i

    #!/bin/bash# declare inte)ersNK8=9NK9=8i' > $NK8 %eL $NK9 @A then

    echo "Coth 4al*es are eL*al"eli' > $NK8 %)t $NK9 @A then

    echo "NK8 is )reater then NK9"else

    echo "NK9 is )reater then NK8"'i

    19.2. String 0omparisons

    ? e-ual

  • 7/25/2019 Bash Scripting Tutorial

    11/22

    elseecho "Strin)s are N-T eL*al"

    'i

    #!/bin/bash#.eclare strin) S8S8="Cash"#.eclare strin) S9S9="Cash"i' > $S8 = $S9 @A then

    echo "Coth Strin)s are eL*al"else

    echo "Strin)s are N-T eL*al"'i

    11. Bash ile Testing

    0b )ilename Block special )ile

    0c )ilename Special character )ile

    0d director'name %heck )or director' existence

    0e )ilename %heck )or )ile existence

    0) )ilename %heck )or regular )ile existence not a director'

    0G )ilename %heck i) )ile exists and is oned b' e))ective group #(.

    0g )ilename true i) )ile exists and is set0group0id.

    0k )ilename Stick' bit

    0L )ilename S'mbolic link

    01 )ilename $rue i) )ile exists and is oned b' the e))ective user id.

    0r )ilename %heck i) )ile is a readable

    0S )ilename %heck i) )ile is socket

    0s )ilename %heck i) )ile is nonAero siAe

    0u )ilename %heck i) )ile set0ser0id bit is set

    0 )ilename %heck i) )ile is ritable

    0x )ilename %heck i) )ile is executable#!/bin/bash'ile="/'ile"i' > %e $'ile @A then

    echo "ile eists"else

    echo "ile does not eists"'i

    11

  • 7/25/2019 Bash Scripting Tutorial

    12/22

    Similarl' )or example e can use hile loop to check i) )ile does not exists. $his script ill sleepuntil )ile does exists. +ote bash negator 3 ! %e ('ile @A do# Sleep *ntil 'ile does eists/is createdsleep 8done

    12. $oops12.1. Bash 5or loop

    #!/bin/bash

    # bash 'or loop'or ' in $0 ls /var/ 3A do

    echo $'done

    !unning )or loop )rom bash shell command line5

    $ 'or ' in $0 ls /var/ 3A do echo $'A done

    12.2. Bash *hile loop

    #!/bin/bash-NT=Q# bash while loop

    12

  • 7/25/2019 Bash Scripting Tutorial

    13/22

    while > $-NT %)t ? @A doecho 4al*e o' co*nt isB $-NTlet -NT=-NT%8

    done

    12.. Bash until loop

    #!/bin/bash-NT=?# bash *ntil loop*ntil > $-NT %)t @A do echo 4al*e o' co*nt isB $-NT

    let -NT=-NT8done

    12.%. 0ontrol bash loop *ith

    Here is a example o) hile loop controlled b' standard input. "ntil the redirection chain )romS$(1"$ to S$(#+ to the read command exists the hile loop continues.

    #!/bin/bash# This bash script will locate and replace spaces# in the 'ilenaes.IR=""# ontrollin) a loop with bash read coand b( redirectin) ST.-T as# a ST.IN to while loop# 'ind will not tr*ncate 'ilenaes containin) spaces'ind $.IR %t(pe ' while read 'ileA do# *sin) J-SI class >BspaceB@ to 'ind space in the 'ilenaei' >> "$'ile" = U>>BspaceB@@U @@A then# s*bstit*te space with "" character and conseL*entl( renae the 'ilev "$'ile" Eecho $'ile tr ; ; ;;E'iA# end o' while loopdone

    13

  • 7/25/2019 Bash Scripting Tutorial

    14/22

    1. Bash unctions

    !/bin/bash# C5SH NTI-NS 5N C+ .+,5R+. IN 5N2 -R.+R'*nction '*nctionC 6 echo *nction C7'*nction '*nction5 6

    echo $87'*nction '*nction. 6 echo *nction .7'*nction '*nction 6 echo $87# NTI-N 5,,S# Jass paraeter to '*nction 5'*nction5 "*nction 5"'*nctionC# Jass paraeter to '*nction '*nction "*nction "'*nction.

    1%. Bash Select

    #!/bin/bashJS:=;hoose one wordB ;

    # bash selectselect word in "lin*" "bash" "scriptin)" "t*torial"do echo "The word (o* have selected isB $word"# CreaDF otherwise endless loop breaD

    14

  • 7/25/2019 Bash Scripting Tutorial

    15/22

    done

    eit ?

    1'. 0ase statement conditional

    #!/bin/bashecho "What is (o*r pre'erred pro)rain) / scriptin) lan)*a)e"echo "83 bash"echo "93 perl"echo ":3 ph(ton"

    echo "M3 c"echo "3 I do not Dnow !"read caseA#siple case bash str*ct*re# note in this case $case is variable and does not have to# be naed case this is V*st an eaplecase $case in 83 echo "2o* selected bash"AA 93 echo "2o* selected perl"AA :3 echo "2o* selected ph(ton"AA M3 echo "2o* selected c"AA 3 eitesac

    1+. Bash ;uotes and ;uotations

    /uotations and -uotes are important part o) bash and bash scripting. Here are some bash -uotesand -uotations basics.

    1+.1. (scaping

  • 7/25/2019 Bash Scripting Tutorial

    16/22

    characters ill be read b' bash literall'. $o do this e need to use backslash 33 character.Example5

    #!/bin/bash#.eclare bash strin) variableC5SH45R="Cash Script"

    # echo variable C5SH45Recho $C5SH45R

    #when eta character s*ch *s "$" is escaped with "" it will be read literall(echo $C5SH45R

    # bacDslash has also special eanin) and it can be s*ppressed with (et another""echo ""

    1+.2. Single ;uotes

    Single -uotes in bash ill suppress special meaning o) ever' meta characters. $here)ore metacharacters ill be read literall'. #t is not possible to use another single -uote ithin to single-uotes not even i) the single -uote is escaped b' backslash.

    #!/bin/bash#.eclare bash strin) variableC5SH45R="Cash Script"# echo variable C5SH45Recho $C5SH45R# eta characters special eanin) in bash is s*ppressed when *sin) sin)leL*otesecho ;$C5SH45R "$C5SH45R";

    1+.. 4ouble =uotes

    (ouble -uotes in bash ill suppress special meaning o) ever' meta characters except 3C32 33 and3D3. &n' other meta characters ill be read literall'. #t is also possible to use single -uote ithindouble -uotes. #) e need to use double -uotes ithin double -uotes bash can read them literall'hen escaping them ith 33. Example5

    16

  • 7/25/2019 Bash Scripting Tutorial

    17/22

    #!/bin/bash#.eclare bash strin) variableC5SH45R="Cash Script"

    # echo variable C5SH45Recho $C5SH45R

    # eta characters and its special eanin) in bash is# s*ppressed when *sin) do*ble L*otes ecept "$"F "" and "E"

    echo "It;s $C5SH45R and "$C5SH45R" *sin) bacDticDsB EdateE"

    1+.%. Bash ;uoting *ith 8S>0 st3le

    $here is also another t'pe o) -uoting and that is &+S#0%. #n this t'pe o) -uoting charactersescaped ith 33 ill gain special meaning according to the &+S#0% standard.

    a alert 7bell8 b backspace

    e an escape character ) )orm )eed

    n neline r carriage return

    t horiAontal tab v vertical tab

    backslash D single -uote

    nnn

    octal value o) characters 7 see

    :http5**.asciitable.com* &S%##table; 8 xnn

    hexadecimal value o) characters 7 see

    :http5**.asciitable.com* &S%##table; 8

    $he s'ntax )o ansi0c bash -uoting is5 C44 . Here is an example5

    #!/bin/bash# as a eaple we have *sed n as a new lineF M? is he val*e 'or # and Q is octal val*e 'or echo $;webB wwwlin*con'i)or)neailB webM?lin*con'i)Qor);

    1/. rithmetic ?perations

    1/.1. Bash ddition 0alculator ()ample

    17

  • 7/25/2019 Bash Scripting Tutorial

    18/22

    #!/bin/bashlet R+S,T8=$8$9echo $8$9=$R+S,T8 ; %< # let R+S,T8=$8$9;declare %i R+S,T9R+S,T9=$8$9echo $8$9=$R+S,T9 ; %< # declare %i R+S,T9A R+S,T9=$8$9;echo $8$9=$00$8 $933 ; %< # $00$8 $933;

    1/.2. Bash rithmetics

    #!/bin/bashecho ;### let ###;# bash additionlet 5..ITI-N=:echo ": =" $5..ITI-N

    # bash s*btractionlet SCTR5TI-N=%Xecho " % X =" $SCTR5TI-N

    # bash *ltiplicationlet K,TIJ,I5TI-N=UXecho " U X =" $K,TIJ,I5TI-N

    # bash divisionlet .I4ISI-N=M/9

    echo "M / 9 =" $.I4ISI-N

    # bash od*l*slet K-.,S=Y1Mecho "Y 1 M =" $K-.,S

    # bash power o' twolet J-W+R-TW-=9UU9echo "9 Z 9 =" $J-W+R-TW-

    echo ;### Cash 5rithetic +pansion ###;# There are two 'orats 'or arithetic epansionB $> epression @# and $00 epression #33 its (o*r choice which (o* *se

    echo M = $00M 33echo % = $> % @echo M Q = $00: U 933echo Q / : = $00Q / :33echo X 1 = $00X 1 33echo 9 Z X = $> 9 UU X @

    18

  • 7/25/2019 Bash Scripting Tutorial

    19/22

    echo ;### .eclare ###;

    echo %e "Jlease enter two n*bers c"# read *ser inp*tread n*8 n*9declare %i res*ltres*lt=$n*8$n*9echo "Res*lt isB$res*lt "

    # bash convert binar( n*ber 8???8res*lt=9#8???8echo $res*lt

    # bash convert octal n*ber 8Qres*lt=X#8Qecho $res*lt

    # bash convert he n*ber ?+Q5res*lt=8Q#+Q5echo $res*lt

    1/.. ,ound 5loating point number

    #!/bin/bash# )et 'loatin) point n*ber'loatin)pointn*ber=::MMQecho $'loatin)pointn*ber

    # ro*nd 'loatin) point n*ber with bash'or bashro*ndedn*ber in $0print' 1?' $'loatin)pointn*ber3A doecho "Ro*nded n*ber with bashB" $bashro*ndedn*berdone

    19

  • 7/25/2019 Bash Scripting Tutorial

    20/22

    1/.%. Bash 5loating point calculations

    #!/bin/bash# Siple lin* bash calc*latorecho "+nter inp*tB"read *serinp*techo "Res*lt with 9 di)its a'ter decial pointB"

    echo "scale=9A $6*serinp*t7" bcecho "Res*lt with 8? di)its a'ter decial pointB"echo "scale=8?A $6*serinp*t7" bcecho "Res*lt as ro*nded inte)erB"echo $*serinp*t bc

    1. ,edirections

    1.1. ST4?-T 5rom bash script to ST4(,,

    #!/bin/bashecho "Redirect this ST.-T to ST.+RR" 8

  • 7/25/2019 Bash Scripting Tutorial

    21/22

    $o prove that S$(E!! is redirected to S$(1"$ e can redirect script4s output to )ile5

    1.. stdout to screen

    $he simple a' to redirect a standard output 7 stdout 8 is to simpl' use an' command2 becauseb' de)ault stdout is automaticall' redirected to screen. ,irst create a )ile 3)ile@35

    $ to*ch 'ile8$ ls 'ile8'ile8

    &s 'ou can see )rom the example above execution o) ls command produces S$(1"$ hich b'de)ault is redirected to screen.

    1.%. stdout to 5ile

    $he override the de)ault behavior o) S$(1"$ e can use 3>3 to redirect this output to )ile5

    $ ls 'ile8 < ST.-T$ cat ST.-T'ile8

    1.'. stderr to 5ile

    B' de)ault S$(E!! is displa'ed on the screen5

    $ ls'ile8 ST.-T$ ls 'ile9lsB cannot access 'ile9B No s*ch 'ile or director(

    #n the )olloing example e ill redirect the standard error 7 stderr 8 to a )ile and stdout to a

    screen as de)ault. Please note that S$(1"$ is displa'ed on the screen2 hoever S$(E!! isredirected to a )ile called S$(E!!5

    $ ls'ile8 ST.-T$ ls 'ile8 'ile9 9< ST.+RR'ile8$ cat ST.+RRlsB cannot access 'ile9B No s*ch 'ile or director(

    21

  • 7/25/2019 Bash Scripting Tutorial

    22/22

    1.+. stdout to stderr

    #t is also possible to redirect S$(1"$ and S$(E!! to the same )ile. #n the next example eill redirect S$(1"$ to the same descriptor as S$(E!!. Both S$(1"$ and S$(E!! ill beredirected to )ile 3S$(E!!6S$(1"$3.

    $ ls'ile8 ST.+RR ST.-T$ ls 'ile8 'ile9 9< ST.+RRST.-T 8