tash scrkt

Upload: nabeel-sidhu

Post on 21-Feb-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/24/2019 tash scrkt

    1/50

    Sheridan College - Victor Ralevich 1of 50UNIX/LINUX BASH Programming 1

    UNIX

    BASH Programming (Part 1)

  • 7/24/2019 tash scrkt

    2/50

    Sheridan College - Victor Ralevich 2of 50UNIX/LINUX BASH Programming 1

    UNIX

    BASH Programming

    Topics:

    Shells Running a BASH Script Shell Variables and Related Commands Passing Arguments to Shell Scripts Program Control Flow Commands (if)

    Arithmetic Operators

  • 7/24/2019 tash scrkt

    3/50

    Sheridan College - Victor Ralevich 3of 50UNIX/LINUX BASH Programming 1

    Shell Scripts

    The shell scriptis a file that contains series of commandsto be executed by the shell.

    There are three ways to execute Bash shell script:

    oBy making the shell script file an executable file usingchmodcommand,

    oBy running the /bin/bash command with the script file asits parameter (/bin/bash script_file), or

    oBegin a shell script with #!/bin/bash.

  • 7/24/2019 tash scrkt

    4/50

    Sheridan College - Victor Ralevich 4of 50UNIX/LINUX BASH Programming 1

    Command: echo

    echo[flags][file-list]

    Purpose Print-to-screen functionFlags\b\c

    \f

    \n\t

    Moves already printed text back one space.Forces the following command to appear on the sameline as the current command.

    Forces the following command to appear on the nextline at a specified horizontal location.Forces the following command to appear on a new line.Indents the following command output by one tab.

  • 7/24/2019 tash scrkt

    5/50

    Sheridan College - Victor Ralevich 5of 50UNIX/LINUX BASH Programming 1

    Example:

    $cat whoson#!/bin/bash

    dateecho Users Currently Logged Inwho

    $chmod u+x whoson$whoson

    Fri Jun 17 10:59:40 PDT 1994Users Currently Logged In

    alex tty1 Jun 17 08:26Jenny tty02 Jun 17 10:04

  • 7/24/2019 tash scrkt

    6/50

    Sheridan College - Victor Ralevich 6of 50UNIX/LINUX BASH Programming 1

    The dotcommand

    The dotcommand ( . ) is a built-in shell command thatlets you execute a program in the current shell and

    prevents the shell from creating the child process.

    There is a space between the dot command and itsargument.

    $ . whoson

    If your login shell is not set up to search for executablefiles in the working directory, try command:

    $./whoson

  • 7/24/2019 tash scrkt

    7/50

    Sheridan College - Victor Ralevich 7of 50UNIX/LINUX BASH Programming 1

    ShellVariables and Related Commands

    Shell environment variablesare used to customize theenvironment in which the shell runs.

    A copy of environment variables as passed to everycommand that executes in the shell as its child.

    Most of these variables are initialized when/etc/profileexecutes at login time.

    It is possible to customize these variables in users~/.profile statrtup file, or the ~/.bashrc,~/.bash_login, and ~/.bash_profilefiles.

  • 7/24/2019 tash scrkt

    8/50

    Sheridan College - Victor Ralevich 8of 50UNIX/LINUX BASH Programming 1

    Some Important Writable Bash Environment VariablesBASH Full pathname to bash.CDPATH Contains directory names that are searched.EDITOR Default editor.ENV Path to look for configuration files.

    HISTFILE Pathname of the history file.HOME Name of the home directory.PATH Users search path.PPID Parents process ID.

    PS1 Primary shell prompt on command line.PS2 Secondary shell prompt.PWD Name of the currently working directory.TERM Type of users console terminal.

  • 7/24/2019 tash scrkt

    9/50

    Sheridan College - Victor Ralevich 9of 50UNIX/LINUX BASH Programming 1

    Read-Only Bash Environment Variables$0 Name of program.$1 - $9 Values of command-line arguments.$* Values of all command line arguments.$@ Values of all command line arguments; each argument

    is argument individually quoted if $@ is enclosed inquotes.

    $# Total number of command-line arguments.$$ PID of current process.$? Exit status of the most recent command.$! PID of the most recent background process.

    Commands set, declareor envwithout arguments

    are used to see the list of values of the Bash environmentvariables.

  • 7/24/2019 tash scrkt

    10/50

    Sheridan College - Victor Ralevich 10of 50UNIX/LINUX BASH Programming 1

    The shiftcommand - promotes each of the commandline arguments. The second $2becomes the first $1....Successive shift commands make additional argumentsavailable. There is no unshift command to bring back

    arguments that are no longer available.

    $cat demo_shiftecho arg1=$1 arg2=$2 arg3=$3

    shiftecho arg1=$1 arg2=$2 arg3=$3

    $demo_shift alice helen jenny

    arg1=alice arg2=helen arg3=jennyarg1=helen arg2=jenny arg3=

  • 7/24/2019 tash scrkt

    11/50

    Sheridan College - Victor Ralevich 11of 50UNIX/LINUX BASH Programming 1

    The setcommand. When you call setcommand with oneor more arguments, it sets the values of the command lineargument variables ($1- $9) to its arguments.

    The setcommand may be used to cause it to use thestandard output of another command as its arguments.

  • 7/24/2019 tash scrkt

    12/50

    Sheridan College - Victor Ralevich 12of 50UNIX/LINUX BASH Programming 1

    $dateFri Jun 17 23:04:09 PDT 1996$cat datesetset `date`

    echo $*echo Argument 1: $1echo Argument 2: $2echo Argument 4: $4

    echo $2 $3, $6$datasetFri Jun 17 23:04:09 PDT 1996Argument 1: Fri

    Argument 2: JunArgument 4: 23:04:13Jun 17, 1996

  • 7/24/2019 tash scrkt

    13/50

    Sheridan College - Victor Ralevich 13of 50UNIX/LINUX BASH Programming 1

    Without any arguments, set displays a list of all variablesthat are set. It displays user-created variables as well asshell keyword variables.

    The shell stores the PID number of the process that isexecuting it in the $$variable. The shell substitutes thevalue of $$before it forks a new process to run acommand. The example below demonstrates that the shell

    creates a new shell process when it runs a shell script.

  • 7/24/2019 tash scrkt

    14/50

    Sheridan College - Victor Ralevich 14of 50UNIX/LINUX BASH Programming 1

    $cat id1echo $0 PID = $$$echo $$14137

    $id1id1 PID = 15253$echo $$14137

    Number 14137 is the PID of the login shell, and 15253 is thePID of the subshell.

  • 7/24/2019 tash scrkt

    15/50

    Sheridan College - Victor Ralevich 15of 50UNIX/LINUX BASH Programming 1

    Shell stores the exit status of the last command in the $?variable. Nonzero exit means that the command failed.Exit status may be specified using an exit command,followed by a number, to terminate the script.

    $cat esecho Hi!exit 7

    $esHi!$echo $?7

    $echo $?0

  • 7/24/2019 tash scrkt

    16/50

    Sheridan College - Victor Ralevich 16of 50UNIX/LINUX BASH Programming 1

    Example:

    $ set One Two Three$ echo $3 $2 $1

    Three Two One

    $ set `date`$ echo $1 $2 $3

    Wed Nov 29

  • 7/24/2019 tash scrkt

    17/50

    Sheridan College - Victor Ralevich 17of 50UNIX/LINUX BASH Programming 1

    Prompt characters\H Domain name of the host\T Time in 12 hours hh:mm:ssformat\d The date in weekday month date format\h Host name up to the first dot

    \s The shell name\t Time in 24 hour hh:mm:ssformat\u User name of the current user\v Version of the Bash shell

    \w Current working directory

    Examples:

    PS1=\w$PS1=\ht

  • 7/24/2019 tash scrkt

    18/50

    Sheridan College - Victor Ralevich 18of 50UNIX/LINUX BASH Programming 1

    User-defined variables

    Name of the variable may be any sequence of letters anddigits with letter as the first character.

    When you assign a value to a variable, you must notprecede or follow the equal sign with a Space or Tab.

    Bash does not require the type declaration but declareand typeset commands can be used to declare variablestype.

    All Bash variable is string by default, but can be declaredto be an integer.

  • 7/24/2019 tash scrkt

    19/50

    Sheridan College - Victor Ralevich 19of 50UNIX/LINUX BASH Programming 1

    Use echoto display their values.

    The shell substitutes the value of a variable when youprecede the name of the variable with a dollar sign ($).

    $person=alex $echo $person$person

    $echo person

    person $echo \$person$person

    $echo $personalex

    $echo $personalex

  • 7/24/2019 tash scrkt

    20/50

    Sheridan College - Victor Ralevich 20of 50UNIX/LINUX BASH Programming 1

    Double quotations marks are used to assign or display avalue that contains Space or Tab to a variable.

    $person=alex and jenny

    $echo $personalex and jenny

    The special characters such as * and ? should also be

    quoted.

    $memo=alex*$echo $memo

    alex*

  • 7/24/2019 tash scrkt

    21/50

    Sheridan College - Victor Ralevich 21of 50UNIX/LINUX BASH Programming 1

    $echo $memoalex.report alex.summary

    $ls

    alex.reportalex.summary

    To remove the value of a variable, set it to null:

    $person=

    or use unsetcommand:

    $unset person

  • 7/24/2019 tash scrkt

    22/50

    Sheridan College - Victor Ralevich 22of 50UNIX/LINUX BASH Programming 1

    The readonlycommand is used to ensure that thevalue of a variable cannot be changed. Assign a value toa variable before you declare it to be readonly.

    $readonly person

    The readonlycommand without an argument, displaysa list of all user-created readonly variables.

    In case of use of exportcommand with a variable nameas an argument, the shell places the value of the variablein the calling environment of child process.

  • 7/24/2019 tash scrkt

    23/50

    Sheridan College - Victor Ralevich 23of 50UNIX/LINUX BASH Programming 1

    $cat test1feline=lionecho test1 1: $felinesubtestecho test1 2: $feline$cat subtestecho subtest 1:$felinefeline=tiger

    echo subtest 2:$feline$test1test1 1: lion

    subtest 1:subtest 2: tigertest1 2: lion

    $cat test2export felinefeline=lionecho test2 1: $felinesubtestecho test2 2: $feline$test2test2 1: lion

    subtest 1: lionsubtest 2: tigertest2 2: lion

  • 7/24/2019 tash scrkt

    24/50

    Sheridan College - Victor Ralevich 24of 50UNIX/LINUX BASH Programming 1

    The readcommand reads one line from the standardinput and assigns the line to one or more variables.

    If you enter more words than readhas variables, read

    assigns one word to each variable, with all the left-overwords going to the last variable.

    If input contains special characters, and you want them to

    be just values of variables, use double quotes.

    If you want the shell to use the special meanings of thespecial characters, do not use quotation marks.

  • 7/24/2019 tash scrkt

    25/50

    Sheridan College - Victor Ralevich 25of 50UNIX/LINUX BASH Programming 1

    Example:

    $cat readxecho Enter a command: \c

    read command$commandecho Thanks

    $readxEnter a command: whoalex tty11 Jun 17 07:09scott tty7 Jun 17 08:23

    Thanks

  • 7/24/2019 tash scrkt

    26/50

    Sheridan College - Victor Ralevich 26of 50UNIX/LINUX BASH Programming 1

    Example:

    $cat readc

    echo Enter something: \cread word1 word2echo Word 1 is: $word1echo Word 2 is: $word2

    $readcEnter something: Monty Pythons FlyingCircus

    Word 1 is: MontyWord 2 is: Pythons Flying Circus

  • 7/24/2019 tash scrkt

    27/50

    Sheridan College - Victor Ralevich 27of 50UNIX/LINUX BASH Programming 1

    When you enclose a command between two backquotes(`), the shell replaces the command with the output of thecommand (command substitution).

    $cat direcho You are using the `pwd` directory.

    $dir

    You are using the /home/jenny directory.

  • 7/24/2019 tash scrkt

    28/50

    Sheridan College - Victor Ralevich 28of 50UNIX/LINUX BASH Programming 1

    Control-Flow Commands

    The control-flow commands alter the order of execution ofcommands within a shell script.

    if ... then

    iftest conditionthen

    commandsfi

    The test condition is relational expression that might haveone out of two values: trueor false.

  • 7/24/2019 tash scrkt

    29/50

    Sheridan College - Victor Ralevich 29of 50UNIX/LINUX BASH Programming 1

    There are two different formats for the test expression:

    testexpression

    [expression]

    The expressioncontains one or more criteria evaluatedby test:

    -a separating two criteria is a logical AND operator,-o is a logical OR operator,! is NOT operator.

    Operator -atakes precedence over -o.

  • 7/24/2019 tash scrkt

    30/50

    Sheridan College - Victor Ralevich 30of 50UNIX/LINUX BASH Programming 1

    Operators for the testCommand String Testing

    string True if stringis not null string.-nstring True if stringhas a length greater than zero.

    -zstring True if stringhas length zero.

    string1=string2 True if string1and string2are the same.

    string1!=string2True if string1and string2are not the same.

    Operators for the testCommand Integer Testing

    int1relop int2 The relop is relational operator:

    -gt greater than-ge greater than or equal-eq equal to-ne not equal to

    -le less than or equal to-lt less than

  • 7/24/2019 tash scrkt

    31/50

    Sheridan College - Victor Ralevich 31of 50UNIX/LINUX BASH Programming 1

    Operators for the testCommand File Testing

    -dfile True if fileexists and is directory.

    -ffile True if fileexists and is an ordinary file.

    -Lfile True if fileexists and is a symbolic link.

    -rfile True if fileexists and you have read access permission.-sfile True if fileexists and contains information.

    -wfile True if fileexists and you have write access permission.

    -xfile True if fileexists and you have execute access permission.

  • 7/24/2019 tash scrkt

    32/50

    Sheridan College - Victor Ralevich 32of 50UNIX/LINUX BASH Programming 1

    Example:#!/bin/bashecho Enter filename: \cread filename

    if [-r $filename -a -s $filename]thenecho File $filename exists and is not empty.echo You have read access permission to the file.

    fi

  • 7/24/2019 tash scrkt

    33/50

    Sheridan College - Victor Ralevich 33of 50UNIX/LINUX BASH Programming 1

    if ... then ... else

    iftest-conditionthen

    commandselsecommands

    fi

    If the test-command returns a truevalue, if structureexecutes the commands between thenand elsestatements and then passes control to fi, and the shell

    continues with the next command in the script. If the test-command returns a falsestatus, it executes thecommands following the elsestatement.

  • 7/24/2019 tash scrkt

    34/50

    Sheridan College - Victor Ralevich 34of 50UNIX/LINUX BASH Programming 1

    Example:

    $cat AreYouOK#!/bin/bash

    echo Are you OK? #User promptecho input Y for yes and N for no:\cread answerif test $answer = Y

    thenecho Glad to hear that.else

    echo Hope youll get better soon.

    fi

  • 7/24/2019 tash scrkt

    35/50

    Sheridan College - Victor Ralevich 35of 50UNIX/LINUX BASH Programming 1

    if ... then ... elif

    iftest-statementthen

    commandseliftest-command

    then

    commands

    elsecommands

    fi

  • 7/24/2019 tash scrkt

    36/50

    Sheridan College - Victor Ralevich 36of 50UNIX/LINUX BASH Programming 1

    The elifstatement combines elseand ifstatementsand allows construction of a nested set of if ... then...elsestructures.

    Example:

    #!/bin/bashecho word 1: \c

    read word1echo word 2: \cread word2echo word 3: \c

    read word3

  • 7/24/2019 tash scrkt

    37/50

    Sheridan College - Victor Ralevich 37of 50UNIX/LINUX BASH Programming 1

    if [$word1=$word2 -a $word2=$word3]then

    echo Match: words 1, 2 & 3elif [$word1 = $word2]

    thenecho Match: words 1 & 2elif [$word1 = $word3]

    then

    echo Match: words 1 & 3elif [$word2 = word3]then

    echo Match: words 2 & 3

    elseecho No matchfi

  • 7/24/2019 tash scrkt

    38/50

    Sheridan College - Victor Ralevich 38of 50UNIX/LINUX BASH Programming 1

    Arithmetic Operations in BASH

    The values are stored in Bash as strings. The Bourneshell does not include a simple, built-in operator for

    arithmetic and logic operations.

    Example:

    $x=20$echo $x20$x=$x+1

    $echo $x20+1

  • 7/24/2019 tash scrkt

    39/50

    Sheridan College - Victor Ralevich 39of 50UNIX/LINUX BASH Programming 1

    The shell did not add number 1to the value of x. Itconcatenated the string +1to the string value of x.

    There are three ways to perform arithmetic on numeric

    data in Bash:

    oBy using the letcommand,oBy using the shell expression $((expression)), and

    oBy using the exprcommand.

    The expression evaluation is performed in long integersand no overflow check is performed.

  • 7/24/2019 tash scrkt

    40/50

    Sheridan College - Victor Ralevich 40of 50UNIX/LINUX BASH Programming 1

    The Bash letcommand is used to evaluate thearithmetic expressions by specifying them as arguments.

    letexpression-list

    If expression contains space characters it has to besurrounded by double quotes.

    $let x = 2 y = 3$let z=x**y$echo The values of z is $z

    The value of z is 8

  • 7/24/2019 tash scrkt

    41/50

    Sheridan College - Victor Ralevich 41of 50UNIX/LINUX BASH Programming 1

    In $((expression))

    the value of expressionis calculated and the result is

    returned.

    $x=2 y=3$echo The value of z=x*y is $((x*y))

    The value of z=x*y is 8

    $let i=5$let i=i+1

    $echo $i6

  • 7/24/2019 tash scrkt

    42/50

    Sheridan College - Victor Ralevich 42of 50UNIX/LINUX BASH Programming 1

    $x=3$((x=x-2))$echo $x1

    Commandexprargs

    provides arithmetic operations capability and evaluateseither numeric or nonnumeric character strings.

    The exprcommand takes the arguments as

    expressions, evaluates them, and displays the results onthe standard output device.

  • 7/24/2019 tash scrkt

    43/50

    Sheridan College - Victor Ralevich 43of 50UNIX/LINUX BASH Programming 1

    Arguments may be arithmetic, relational, logical, andstring manipulation related expressions.

    Example:

    $expr 7 12-5

    $expr 2.5 1.2expr: nonnumeric argument

    Both Bourne Shell and BASH support only integer

    arithmetic.

  • 7/24/2019 tash scrkt

    44/50

    Sheridan College - Victor Ralevich 44of 50UNIX/LINUX BASH Programming 1

    Because the * (multiplication) and % (reminder)characters have special meaning to the shell, they mustbe preceded by a backslash (\) for the shell to ignoretheir special meanings.

    $expr 15/35$expr 12\*336

    $expr 10\%31

    The exprutility returns exit status of 0 if the expression

    is neither a null string nor the number 0, a status of 1 ifthe expression is null or 0, and status of 2 if theexpression is invalid.

  • 7/24/2019 tash scrkt

    45/50

    Sheridan College - Victor Ralevich 45of 50UNIX/LINUX BASH Programming 1

    The single back quotations ( ` ) surrounding thecommand cause the output of the command to exprtobe substituted.

    $x=10$x=`expr $x+2`$echo $x12

    The exprcommand provides relational operators thatwork on both numeric and nonnumeric arguments.

  • 7/24/2019 tash scrkt

    46/50

    Sheridan College - Victor Ralevich 46of 50UNIX/LINUX BASH Programming 1

    If both arguments are numeric, the comparison isnumeric. If one or both arguments are nonnumeric, thecomparison is nonnumeric and uses the ASCII values.

    The relational operators are: =, !=, =

    The exprcommand displays 1 when the comparison istrue, and 0 when comparison is false.

    Because the > (greater than) and < (less than) charactershave special meaning to the shell, they must beproceeded by a backslash ( \ ) for the shell to ignore their

    special meaning.

  • 7/24/2019 tash scrkt

    47/50

    Sheridan College - Victor Ralevich 47of 50UNIX/LINUX BASH Programming 1

    Example:

    $ expr 10\200

    Variables can be declared as integers with the

    declare i

    command. If you attempt to assign any string value, Bash

    assigns 0 to the variable.

  • 7/24/2019 tash scrkt

    48/50

    Sheridan College - Victor Ralevich 48of 50UNIX/LINUX BASH Programming 1

    Numbers can also be represented in different bases,binary, octal, hex using expression:

    variable=base#number

    Examples:

    $declare i x=017 #octal number

    $echo $x15

    $x=2#101

    $echo $x5

  • 7/24/2019 tash scrkt

    49/50

    Sheridan College - Victor Ralevich 49of 50UNIX/LINUX BASH Programming 1

    $x=16#b$echo $x11

    $ declare i num$ num=hello$ echo $num0

    $num=5+5$echo $num10

  • 7/24/2019 tash scrkt

    50/50

    Sheridan College - Victor Ralevich 50of 50UNIX/LINUX BASH Programming 1

    $num=4 * 5$echo $num20

    $num=4*5$echo $num20

    $num=4 * 5$echo $numbash: *: command not found