lec12 basic scripts

Upload: kallbaqi

Post on 04-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Lec12 Basic Scripts

    1/19

    CS 497C Introduction to UNIXLecture 32: - Shell Programming

    Chin-Chih Chang

    mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/30/2019 Lec12 Basic Scripts

    2/19

    1.2

    The shell is also a programming languagethat executes shell scripts in the interpretivemode one line at a time.Shell scripts run slower than compiledlanguages like , but for many jobs speed isno hurdle.

    is more used as a language for the

    system administration. An UNIX systemadministrator is supposed to be anaccomplished shell programmer.

  • 7/30/2019 Lec12 Basic Scripts

    3/19

    1.3

    The shell of LinuxLinux has a variety of different shells:

    Bourne shell (sh), C shell (csh), Korn shell (ksh), TCshell (tcsh), Bourne Again shell (bash).

    Certainly the most popular shell is bash . Bash isthe shell that will appear in the GNU operating

    system. Bash is an sh-compatible shell thatincorporates useful features from the Korn shell(ksh) and C shell (csh).It is intended to conform to the IEEE POSIXP1003.2/ISO 9945.2 Shell and Tools standard.It offers functional improvements over sh for bothprogramming and interactive use.

  • 7/30/2019 Lec12 Basic Scripts

    4/19

    1.4

    Programming or Scripting ?bash is not only an excellent command line shell, but ascripting language in itself. Shell scripting allows us to usethe shell's abilities and to automate a lot of tasks that wouldotherwise require a lot of commands.Difference between programming and scripting languages:

    Programming languages are generally a lot more powerful and a lot

    faster than scripting languages. Programming languages generallystart from source code and are compiled into an executable. Thisexecutable is not easily ported into different operating systems.

    A scripting language also starts from source code, but is notcompiled into an executable. Rather, an interpreter reads the

    instructions in the source file and executes each instruction.Interpreted programs are generally slower than compiled programs.The main advantage is that you can easily port the source file to anyoperating system. bash is a scripting language. Other examples of scripting languages are Perl, Lisp, and Tcl.

  • 7/30/2019 Lec12 Basic Scripts

    5/19

    1.5

    Different levels of scripting1. Simple commands listed in a filemany useful possibilities for administratorschanging passwords, setting up accounts

    2. Using variables and positional parametersmany more possibilities process files (Project 2)

    3. Using complex branches (if) and loops (while)

    you can skip this or explore on your own4. Hugely powerful see Lec11 Advanced Scripts

  • 7/30/2019 Lec12 Basic Scripts

    6/19

    1.6

    The first bash programWe must know how to use a text editor. There aretwo major text editors in Linux:

    vi, emacs (or xemacs). So fire up a text editor; for example:

    $ vi hello.sh &and type the following inside it:

    #!/bin/bashecho Hello World

    The first line tells Linux to use the bash interpreter to run this script. Now, make the script executable:

    $ chmod 700 hello.sh$./hello.sh (if PATH is set properly, just say hello.sh)

    Hello World

  • 7/30/2019 Lec12 Basic Scripts

    7/19

    1.7

    The second bash programWe write a program that copies all files into a directory, andthen deletes the directory along with its contents. This can

    be done with the following commands:$ mkdir trash$ cp * trash$ rm -rf trash$ mkdir trash

    Instead of having to type all that interactively on the shell,write a shell program instead:

    $ cat trash#!/bin/bash

    # this script deletes some filesmkdir trashcp * trashrm -rf trashecho Deleted all files!

  • 7/30/2019 Lec12 Basic Scripts

    8/19

    1.8

    A shell variable is assigned with the = symbolwithout using the $, but is evaluated byprefixing it with a $:

    fname=profile; echo $fnameThe statement removes a variable fromthe shell.Variables are concatenated by placing them

    side by side; no operators are needed:x=foo; y=.doc; z=$x$y; echo $z

  • 7/30/2019 Lec12 Basic Scripts

    9/19

    1.9

    Shell variables can be evaluated by usingcurly braces around the variable name.

    echo ${fname}

    These braces also enable concatenation of avariable and a string.

    echo ${fname}x or echo $ fnamex

    These concatenation features are usefulwhen changing a files extension.

  • 7/30/2019 Lec12 Basic Scripts

    10/19

    1.10

    VariablesWe can use variables as in any programming languages.Their values are always stored as strings, but there aremathematical operators in the shell language that willconvert variables to numbers for calculations.We have no need to declare a variable , just assigning avalue to its reference will create it.

    Example#!/bin/bashSTR= Hello World! echo $STR

    Line 2 creates a variable called STR and assigns the string"Hello World! " to it. Then the value of this variable isretrieved by putting the ' $' in at the beginning.

  • 7/30/2019 Lec12 Basic Scripts

    11/19

    1.11

    Warning !

    The shell programming language does not type-cast its variables. This means that a variable canhold number data or character data.

    count=0count=Sunday

    Switching the TYPE of a variable can lead toconfusion for the writer of the script or someonetrying to modify it, so it is recommended to use avariable for only a single TYPE of data in a script .

    \ is the bash escape character and it preserves theliteral value of the next character that follows.$ ls \*ls: *: No such file or directory

  • 7/30/2019 Lec12 Basic Scripts

    12/19

    1.12

    Single and Double QuoteWhen assigning character data containing spaces or special characters, the data must be enclosed in either

    single or double quotes .Using double quotes to show a string of characters willallow any variables in the quotes to be resolved

    $ var=test string

    $ newvar=Value of var is $ var $ echo $newvarValue of var is test string

    Using single quotes to show a string of characters will not

    allow variable resolution$ var=test string $ newvar=Value of var is $ var $ echo $newvarValue of var is $var

  • 7/30/2019 Lec12 Basic Scripts

    13/19

    1.13

    The export commandThe export command puts a variable into the environmentso it will be accessible to child processes. For instance:

    $ x=hello$ bash # Run a child shell.

    $ echo $x # Nothing in x.$ exit # Return to parent.

    $ export x$ bash$ echo $xhello # It's there.

    If the child modifies x, it will not modify the parents originalvalue. Verify this by changing x in the following way:

    $ x=ciao$ exit$ echo $xhello

  • 7/30/2019 Lec12 Basic Scripts

    14/19

    1.14

    Environmental VariablesThere are two types of variables:

    Local variables

    Environmental variables Environmental variables are set by the system and canusually be found by using the env command. Environmentalvariables hold special values. For instance,

    $ echo $SHELL/bin/bash$ echo $PATH/usr/X11R6/bin:/usr/local/bin:/bin:/usr/bin

    Environmental variables are defined in /etc/profile, /etc/profile.d/ and ~/.bash_profile . These files are theinitialization files and they are read when bash shell isinvoked. When a login shell exits, bash reads~/.bash_logout

  • 7/30/2019 Lec12 Basic Scripts

    15/19

    1.15

    Environmental VariablesHOME: The default argument (home directory) for cd .PATH : The search path for commands. It is a colon-

    separated list of directories that are searched when youtype a command.Usually, we type in the commands in the following way:

    $ ./commandBy setting PATH=$PATH:. our working directory is includedin the search path for commands, and we simply type:

    $ commandIf we type in

    $ mkdir ~/bin

    and we include the following lines in the ~/.bash_profile :PATH=$PATH:$HOME/binexport PATH

    we obtain that the directory /home/rinaldi/bin is included inthe search path for commands.

  • 7/30/2019 Lec12 Basic Scripts

    16/19

    1.16

    Environmental VariablesLOGNAME: contains the user nameHOSTNAME : contains the computer name.

    PS1 : sequence of characters shown before the prompt\t hour \d date\w current directory

    \W last part of the current directory\u user name\$ prompt character

    Example

    [rinaldi@homelinux rinaldi]$ PS1 =ciao \u * ciao rinaldi* _

  • 7/30/2019 Lec12 Basic Scripts

    17/19

    1.17

    Read command

    The read command allows you to prompt for input and storeit in a variable. Example

    #!/bin/bashecho -n Enter name of file to delete: read file

    echo Type 'y' to remove it, 'n' to change yourmind ... rm -i $fileecho "That was YOUR decision!"

    Line 3 creates a variable called file and lets the user enter the filename by typing it. Then the value of this variable isretrieved in the rm command by putting the '$' in at thebeginning.

  • 7/30/2019 Lec12 Basic Scripts

    18/19

    1.18

    Shell ParametersPositional parameters are assigned from the shells argument when it is invoked. Positional parameter N may

    be referenced as ${N}, or as $N when N consists of asingle digit.Special parameters

    $# is the number of parameters passed$0 returns the name of the shell script running as well as its location

    in the filesystem$* gives a single word containing all the parameters passed to thescript$@ gives an array of words containing all the parameters passed tothe script

    $ cat sparameters.sh#!/bin/bashecho $#; $0; $1; $2; $*; $ @ $ sparameters.sh alba chiara2; ./sparameters.sh; alba; chiara; alba chiara; alba

    chiara

  • 7/30/2019 Lec12 Basic Scripts

    19/19

    1.19

    Trash$ cat trash.sh#!/bin/bashif [ $# -eq 1 ];then

    if [ ! d $ HOME/trash ];

    thenmkdir $ HOME/trash

    fimv $1 $ HOME/trash

    elseecho Use : $0 filename exit 1

    fi