Linux Shell (4)

Embed Size (px)

Citation preview

  • 7/31/2019 Linux Shell (4)

    1/30

    The Linux ShellsCreating a Script Part

    IIOperating Systems Laboratory

    Amir Saman Memaripour

  • 7/31/2019 Linux Shell (4)

    2/30

    Standard OutputLinux assumes that all output is going to some kind of

    file. To Linux, the screen is a file called /dev/tty.

    printf Sales are up > /dev/tty # display on the screen

    Bash uses the symbol &1 to refer to standard output, andyou can explicitly redirect messages to it.

    2

  • 7/31/2019 Linux Shell (4)

    3/30

    Standard Outputprintf Sales are up > results.txt # sent to a file on disk

    printf Sales are up > /dev/tty # send explicitly to thescreen

    printf Sales are up # sent to screen via standard output

    printf Sales are up >&1 # same as the last one

    printf Sales are up >/dev/stdout # same as the last one/dev/stdout is another name for the standard output file.

    The last three examples are identical. Make sure &1 isdirectly beside the redirect symbol, with no intervening

    spaces. 3

  • 7/31/2019 Linux Shell (4)

    4/30

    Standard Output$ bash listorders.sh > listing.txt

    Inside the script, standard output no longer refers to thescreen. Instead, standard output refers to the file

    youve redirected the output to, in this case listing.txt.

    ls -l incoming/orders # listing saved in listing.txt

    ls -l incoming/orders 1>&1 # listing saved in listing.txt

    ls -l incoming/orders > /dev/tty # listing displayed onscreen

    4

  • 7/31/2019 Linux Shell (4)

    5/30

    Standard ErrorLinux defines a second file especially for messages

    intended for the user called standard error. This filerepresents the destination for all error messages. Thesymbol for standard error is &2. /dev/stderr can also be

    used. The default destination, like standard output, isthe screen. For example,

    printf $SCRIPT:$LINENO: No files available for

    processing >&2

    5

  • 7/31/2019 Linux Shell (4)

    6/30

    Standard ErrorBecause standard error, like standard output, is a kind of

    renaming of another destination, standard error canlikewise be redirected. The redirection symbols forstandard error are the same as standard output except

    they begin with the number 2.

    $ bash listorders.sh 2> listorders_errors.txt

    In this example, all the error messages from the

    listorders.sh script are saved in the filelistorders_errors.txt.

    6

  • 7/31/2019 Linux Shell (4)

    7/30

    Standard InputLinux treats all input as if it was being read from a file.

    This special file is called standard input, and uses thesymbol &0. /dev/stdin can also be used for standardinput.

    When commands are joined together with the | symbol,the standard input of the second command becomesthe standard output of the first command.

    7

  • 7/31/2019 Linux Shell (4)

    8/30

    Built-In Versus LinuxCommands

    The original Bourne shell was designed in a way that anythingthat was not an essential part of the shell wasimplemented as some program outside of the shell itself.Even arithmetic, for example, had to be performed by anoutside program. This design made the Bourne shell very

    flexible, but it also introduced a couple of drawbacks.

    1. It was slow because programs were constantly loading andrestarting to perform even the simplest of tasks.

    2. It made shell scripts difficult to port because there wereno guarantees that a command on one operating systemwas implemented the same way on another; suchcommands might not even have been available.

    8

  • 7/31/2019 Linux Shell (4)

    9/30

    Built-In Versus LinuxCommands

    To deal with these problems, Bash has many of itsfundamental commands built-in. But for basiccompatibility with the older Bourne shell, Linux stillimplements its own version of Bashs commands.

    For instance, test is a built-in command in Bash, but Linuxalso provides its own program /usr/bin/test for shellsthat dont provide a built-in version of test.

    If you dont know whether a command is built-in, the Bashtype command will tell you. If the command is a Linuxcommand, it shows the path of the command (like theLinux whereis command).

    9

  • 7/31/2019 Linux Shell (4)

    10/30

    Built-In Versus LinuxCommands

    The builtin command explicitly runs a built-in command.The command runs even if theres an alias with thesame name.

    builtin pwd

    Likewise, command explicitly runs a Linux command,even if theres a built-in command or alias with thesame name.

    command pwd

    10

  • 7/31/2019 Linux Shell (4)

    11/30

    Built-In Versus LinuxCommands

    Although built-in and command are useful in testing andporting older scripts to Bash, well-structured scriptsshould not rely on them because they indicateambiguity in a scripts design.

    The built-in enable command temporarily hides the shellbuilt-in commands and reenables them later. The -nswitch disables the command.

    11

  • 7/31/2019 Linux Shell (4)

    12/30

    Built-In Versus LinuxCommands

    $ enable test

    $ type test

    test is a shell builtin$ enable -n test

    $ type test

    test is /usr/bin/test

    12

  • 7/31/2019 Linux Shell (4)

    13/30

    Built-In Versus LinuxCommands

    With -p, all enabled shell built-ins are printed. You cancombine -p with -n to list the disabled built-ins, or use-a to show them all. The -s switch restricts the listing toPOSIX special built-ins.

    $ enable pn

    enable -n test

    13

  • 7/31/2019 Linux Shell (4)

    14/30

    VariablesThe results of commands can be written to a file or saved

    in variables. Because variables are saved in memory,they tend to be faster to examine than files. Bashdoesnt put an upper limit on the size of a variable.

    They are large enough to contain anything you will everneed to hold.

    Variables are declared using the Bash declarecommand. To declare a variable named COST, usethis:

    $ declare COST

    14

  • 7/31/2019 Linux Shell (4)

    15/30

    VariablesAlthough variables can be in upper- or lowercase, tradition

    dictates variables are named in uppercase so as not to beconfused with shell commands, which are almost always inlowercase. TOTAL, ORDERS_EUROPE, and _W3C are alllegitimate variable names. There are no reserved words,

    which are words that are reserved for a specific purpose inthe shell.

    Variables are assigned new values with an equals sign (=). Toassign an empty string to a variable, dont supply any value.

    $ COST=

    Otherwise, include some text to be assigned.

    $ COST=0

    15

  • 7/31/2019 Linux Shell (4)

    16/30

    VariablesBecause declare is a command, variables are created

    only when the declare command is executed. Theyremain in existence until the script ends or until thevariable is destroyed with the built-in unset command.

    $ unset COST

    16

  • 7/31/2019 Linux Shell (4)

    17/30

    VariablesThe results of a command can also be assigned to a

    variable. If a command is contained in backquotes (),everything written to standard output is stored in thevariable being assigned instead.

    $ declare NUMBER_OF_FILES

    $ NUMBER_OF_FILES=ls -1 | wc -l

    $ printf %d $NUMBER_OF_FILES

    14

    17

  • 7/31/2019 Linux Shell (4)

    18/30

    VariablesBash has more than 50 predefined variables. These

    variables, created when Bash is first started, provideinformation about the Bash session and can be usedto control some of the shells features.

    Some of these variables have special properties thatmight be lost if you unset the variable and then create anew one with the same name. For example, thevariable RANDOM contains a random number. If you

    delete RANDOM with unset and declare a new variablecalled RANDOM, this new variable is a normal shellvariable and does not contain random numbers.Therefore, its best to avoid creating variables with thesame name as the predefined variables.

    18

  • 7/31/2019 Linux Shell (4)

    19/30

    The Effect of Quotations$ DISTRIBUTION_CENTERS=London ; Paris ; New

    York

    $ printf %s $DISTRIBUTION_CENTERS

    London;Paris;NewYork

    $ printf %s $DISTRIBUTION_CENTERS

    London ; Paris ; New York

    19

  • 7/31/2019 Linux Shell (4)

    20/30

    The Effect of Quotations$ DISTRIBUTION_CENTERS=London ; Paris ; New York

    $ printf %s $DISTRIBUTION_CENTERS

    London;Paris;NewYork

    $ printf %s $DISTRIBUTION_CENTERS

    London ; Paris ; New York

    It is a safe practice to always enclose variable substitutions with

    quotes.

    20

  • 7/31/2019 Linux Shell (4)

    21/30

    The Effect of QuotationsBesides space interpretation, another effect of quotation

    marks is that no pattern matching is done. Normally, forexample, the asterisk (*) represents all the files in thecurrent directory. Quotation marks prevent the asterisk

    from being replaced with a list of files.$ printf %s\n *

    orders.txtarchive

    calc.sh$ printf %s\n *

    *

    21

  • 7/31/2019 Linux Shell (4)

    22/30

    The Effect of QuotationsTo print strings without interpreting the special characters

    inside, use single quotes. Double quotes do notprevent Bash from interpreting the special characters $,, and \, but single quotes leave all characters

    unchanged.

    $ printf %s $TAX_MESSAGE$TAX_MESSAGE

    In this case, the single quotes prevent Bash frominterpreting the value as a variable substitutionbecause the dollar sign is not treated specially. Thebackslash (\) acts like single quotes for one character,

    leaving the character unchanged. 22

  • 7/31/2019 Linux Shell (4)

    23/30

    Variable AttributesIf a variable is declared with the -i (integer) switch, Bash turns

    on the integer attribute for that variable. The shell willremember that the string should be treated as an integervalue. If a non-numeric value is assigned to an integervariable, Bash does not report an error but instead assigns

    a value of zero.

    $ declare -i NUMBER_ACCOUNTS=15

    $ printf %d\n $NUMBER_ACCOUNTS15

    $ NUMBER_ACCOUNTS=Smith # mistake

    $ printf %d\n $NUMBER_ACCOUNTS0

    23

  • 7/31/2019 Linux Shell (4)

    24/30

    ArraysArrays are lists of values that are created with the -a

    (array) attribute. A number called an indexrefers to theposition item in the array. Bash arrays differ from arraysin other computer languages because they are open-

    ended. Arrays can be any length and are initially filledwith empty strings for items.

    $ declare -a PRODUCTS

    24

  • 7/31/2019 Linux Shell (4)

    25/30

    ArraysNew items are assigned to the array using square

    brackets to indicate the position in the list. The firstposition is position zero (not one). If an initial value isspecified, it is assigned to the first position. Assigning

    one value is not particularly useful but is included forcompatibility with other shells. Alternatively, the initialvalues can be assigned to specific positions byincluding a position in square brackets.

    $ declare -a DEPT[0]=accounting DEPT [1]=shipping \

    DEPT [2]=customer service

    25

  • 7/31/2019 Linux Shell (4)

    26/30

    Exporting VariablesShell variables exist in the script or interactive sessions

    only where they were declared. In order to make shellvariables available outside of their place of origin, theyhave to be declared as exportable. Variables are

    marked as exportable with the export attribute using thedeclare -x (export) switch. Theexportattributeremindsthe shell that you want to export, or provide thevariable, to all programs run by the script.

    For example, the program CVS requires a variable calledCVSROOT to exist for all its programs.

    $ declare -x CVSROOT=/home/cvs/cvsroot

    26

  • 7/31/2019 Linux Shell (4)

    27/30

    The eval CommandBash performs variable substitutions as variables are

    encountered in a command. Before a command is executed,Bash searches the command for all dollar signs and insertsthe value of variables before the command is carried out.Bash performs this substitution once. If a variable containsa value with a dollar sign in it and the value is substitutedinto a command, the value with the dollar sign remainsunchanged.

    $ declare rx COMPANY=Value Book Resellers

    $ declare rx TITLE=$COMPANY

    $ printf %s\n $TITLE

    $COMPANY

    27

  • 7/31/2019 Linux Shell (4)

    28/30

    ExpressionsAn expression is a formula that calculates a value. Bash

    has several built-in commands and functions tocompute expressions, and not all have the same syntaxor features. In some cases there is more than one way

    to calculate the same expression.

    There are also many specialized features for use in rarecases. As a result, few Bash programmers have all thenuances memorized.

    28

  • 7/31/2019 Linux Shell (4)

    29/30

    ExpressionsThere are two common built-in commands that interpret

    expressions.

    The test command checks a wide variety of conditions

    and indicates whether the condition is true or not. Testcan compare files, strings, or numbers. Dont confuse itwith the Linux test command.

    The let command computes an expression and

    assigns the results to a variable in a single command.

    29

  • 7/31/2019 Linux Shell (4)

    30/30

    Assignment (5 points)Write a shell script to provide the following output.

    ~/tmp not found

    Deadline: December 4th, 10:00 AM

    How to deliver?!Via email to [email protected]

    This assignment is mandatory!

    30

    mailto:[email protected]:[email protected]