Docstoc

Shell Script

Document Sample
Shell Script Powered By Docstoc
					Shell Script
Alexander Zangerl
 az@bond.edu.au


 Bond University




                    Shell Script – p.1/40
This is an overview only!
       look at the manpage bash(1) or the scripting guide for full

    
       details
       http://www.tldp.org/LDP/abs/html/
    




                                                           Shell Script – p.2/40
major shell variants
       we’re covering bash and friends, not (t)csh!

    
       see also:
    




          




             http://www.faqs.org/faqs/unix-faq/shel




                                                      Shell Script – p.3/40
what’s a shell script?
        simplest:

     
           sequence of commands typed on the command line

           
        common:
     




           




           list of system commands stored in a file




                                                     Shell Script – p.4/40
when to use/not use shell script
        pro:

     
               small task, repetitive

           
               "quick and dirty" prototyping
           
           




               chaining together smaller tools
        contra:
     




            resource intensive tasks
           




            extensive datastructures needed
           




            network interaction
           




        at the very least a script saves the effort of retyping
     




        command sequence




                                                                  Shell Script – p.5/40
script file syntax
        must start with #!interpreterpath

     
        otherwise not standalone executable
     




        aka. she-bang (from sharp-bang), hash-bang
     
     




        http://wombat.doc.ic.ac.uk/foldoc/foldoc.
        is a two-byte "magic number", tells the kernel how to deal
     




        with the file
        eg:
     




              #!/bin/bash
           




              #!/usr/bin/perl -w
           




        rest of file: commands, one per line or separated by ’;’
     




        see also:
     




            magic, file
           




                                                            Shell Script – p.6/40
invoking a shell script
        variant:

     
            interpreterpath scriptpath

           
        runs script in new shell
     




        variant:
     




            scriptpath
           




        if permissions set, shebang present and interpreter a/v
     




        but beware of $PATH settings!
     




        common:
     




           ./scriptname
           




                                                             Shell Script – p.7/40
shell script is a full-fledged programming
language!
       offered features:

    
           shell variables

          
           flow control
          
          




           shell input/output




                                        Shell Script – p.8/40
special chars
        actually a WAY longer list, only basics here

     
        ; is delimiter for commands
     




        (), {} program grouping
     




        ’ " and \ are for quoting
     




        ‘ for cmd substitution
     




        . for sourcing a file
     




        *,?,[],{} see file globbing
     




        # for comments
     




        $ for variable access, lots of extra features
     




                                                        Shell Script – p.9/40
special tokens
        essentially all the keywords the shell understands

     
        for building conditionals, loops etc.
     




        and also some builtins
     




                                                             Shell Script – p.10/40
shell builtins
        tools that are built into the shell itself

     
        instead of being a separate program
     




        builtin runs in same process, external in subprocess
     




        reason:
     




            starting program is costly, internal execution less so.
           




        see also:
     




            type [-a], help, which
           




                                                               Shell Script – p.11/40
shell variables
        some are builtin

     
        and general user-settable ones
     




        note: ignoring arrays and more complex types
     




        normal variables are internally strings
     




        but can assume numerical meaning in special circumstances
     




        eg:
     




              let, $(())
           




                                                        Shell Script – p.12/40
variable assignment
       varname=value

    
       no spaces around the equal sign!
    




                                          Shell Script – p.13/40
variable substitution/access
        $varname or ${varname}

     
        ocasionally second form is necessary
     




        uninitialised:
     




            empty string if used as string
           




            behaves like 0 if used as number
           




                                               Shell Script – p.14/40
see all variables and functions
        set

     
        displays the whole enviroment and shell functions
     




        (set has lots more adv uses)
     




                                                            Shell Script – p.15/40
variable inheritance
       (most) variables live in a process’ environment

    
       env is passed to subprocesses on fork()
    




       but not back to the parent!
    




       result:
    




           what the child does to a var is lost on exit
          




                                                          Shell Script – p.16/40
special vars
        lots more, these are most important ones

     
        $? exit code of last command
     




        $0 to $9 arguments passed
     




        "$*", "$@" all arguments (mostly quoted)
     




        $# number of args
     




        $$ current PID, $! last background PID
     




        $PATH search path for programs
     




        $IFS input field separator
     




                                                   Shell Script – p.17/40
quoting
       inhibiting interpretation of special characters

    
       " prevents word splitting, partial quoting
    




       eg:
    




             "hello world" is one token for shell
          




       ’ also disables all special chars except ’, full quoting
    




       eg:
    




             ’$$’ means two dollar signs, not the PID
          




       single characters: can be escaped with in(eg): ’why don\’t
    




       you see’
       whenever shell reads quoted text it removes the quotes!
    




                                                             Shell Script – p.18/40
process substitution
        ‘somecommand args‘ makes output of cmd available

     
        NOT the same as a pipe!
     




        eg:
     




              x=‘pwd‘; echo $x
           




              cat ‘ls -l‘
           




        see also:
     




            xargs
           




                                                      Shell Script – p.19/40
file globbing
       wildcard system for paths and filenames

    
       not full regular expressions!
    




       * for zero or more characters (but not names starting with .)
    




       ? for one character
    




       [abcd] for one of the listed chars
    




       {ab,cd} for one of the listed phrases
    




                                                           Shell Script – p.20/40
command grouping
       (cmd; cmd;) runs stuff in subshell

    
       {cmd; cmd;} runs stuff in current shell
    




       distinction important for variables and working dir
    




       eg:
    




             redirecting output of multiple cmds
          




             running sequence of cmds in background
          




                                                             Shell Script – p.21/40
flow control
       loops, conditionals

    
       instances
    




            conditionals
          
          




            for loop
            while loop
          




            until loop
          




            case select
          




            loop control
          




            exiting a shell
          




                              Shell Script – p.22/40
conditionals
       if condition; then something; else something; fi

    
       condition is cmd, exit code governs conditional
    




       often used together with test builtin
    




                                                         Shell Script – p.23/40
for loop
        for varname in list; do something; done

     
        assigns varname tokens from list in turn
     




                                                   Shell Script – p.24/40
while loop
       while condition; do something; done

    
       condition is cmd with exit code
    




       exit code 0 means true
    




                                             Shell Script – p.25/40
until loop
        like while but runs until condition is true

     




                                                      Shell Script – p.26/40
exiting a shell
        exit value

     
        terminates the current shell, returns value to parent
     




        generally 0 means true, everything else false
     




                                                                Shell Script – p.27/40
loop control
       break terminates innermost loop

    
       continue goes to next iteration of innermost loop
    




                                                           Shell Script – p.28/40
case select
        like C case statement

     
        case "$var" in "$cond" ) cmd; cmd; ;; "$cond".... ;; esac
     




        details in the Scripting Guide
     




                                                            Shell Script – p.29/40
test builtin
        convenient tool for comparisons, file tests etc.

     
        test something op something
     




        eg:
     




              test 5 -gt 7
           




        also shortcut: [ 5 -gt 7 ]
     




        note space around brackets!
     




        see also:
     




            help test
           




                                                          Shell Script – p.30/40
alternative conditionals
        using the binary logic operators && and ||

     
        eg:
     




              [ 2 = 4 ] && echo this is weird
           
           




              somethingbroken || echo help me!




                                                     Shell Script – p.31/40
input functions
       read reads token from stdin into var, is builtin

    
       eg:
    




             read x y z
          




       depends on $IFS for splitting
    




       lots of options
    




       select builds menu and prompts user
    




       eg:
    




             select veggie in "beans" "carrots"; do something; done;
          




                                                            Shell Script – p.32/40
output functions
       echo prints arguments, is builtin

    
       eg:
    




             echo "hello world"
          
          




             echo "this is pid $$"




                                           Shell Script – p.33/40
echo and quoted chars
       \n newline

    
       \t tab
    




       \b backspace
    




       \a bell
    




       \" means the quote itself
    




       \$ means a literal dollar sign
    




       \\ means a literal backslash
    




                                        Shell Script – p.34/40
printf
        external tool providing c-like printf(3)

     
        occasionally useful when output too complex for echo
     




                                                         Shell Script – p.35/40
here documents
       special-purpose input redirection

    
       someprogram «delimiter
    




       ...stuff...
    




       delimiter
    




       passes all the text between invocation and delimiter to
    




       program




                                                           Shell Script – p.36/40
aliases
        replacing long command invocation with short token

     
        eg:
     




              alias l=’ls -la’
           




        be careful with variable use!
     




        unquoted: will be resolved when alias is defined
     




                                                          Shell Script – p.37/40
functions
       eg:

    
             function funcname () { cmd; cmd; cmd; }

          
       arguments passed available as $0 ... $n
    




       functions must be defined before use
    




       are just expansions for long sequence of cmds
    




       no variable scoping
    




                                                       Shell Script – p.38/40
modules in shell
       eg:

    
             source filename

          
             . filename
          




       reads file and runs script commands in same shell
    




       not same as backtics!
    




       same shell means variables can be set in sourced script
    




       think configuration options
    




                                                          Shell Script – p.39/40
dynamic code in shell
       eg:

    
             eval cmd args

          
       reads arguments as input to current shell and executes result
    




       eg:
    




             X="ls -la"; eval $X /bin
          




                                                           Shell Script – p.40/40

				
DOCUMENT INFO
Shared By:
Categories:
Tags: Shell, Script
Stats:
views:96
posted:4/26/2010
language:English
pages:40
Description: Shell Script