Docstoc

Shell Script (PDF)

Document Sample
Shell Script (PDF) Powered By Docstoc
					                Shell Script

      Alexander Zangerl az@bond.edu.au

                 Bond University




Shell Script                             1 / 42
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                                             2 / 42
major shell variants
       we’re covering bash and friends, not (t)csh!
       see also:
           http:
           //www.faqs.org/faqs/unix-faq/shell/csh-whynot/




            Shell Script                                    3 / 42
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                                    4 / 42
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                                              5 / 42
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.cgi?shebang
       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                                            6 / 42
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                                         7 / 42
shell script is a full-fledged programming language!
       offered features:
           shellscript
           shell variables
           flow control
           shell input/output
           redirection




            Shell Script                              8 / 42
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
       >, >>, <, & for i/o redirection




            Shell Script                               9 / 42
special tokens
       essentially all the keywords the shell understands
       for building conditionals, loops etc.
       and also some builtins




            Shell Script                                    10 / 42
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                                             11 / 42
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                                           12 / 42
variable assignment
      varname=value
      no spaces around the equal sign!




           Shell Script                  13 / 42
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                      14 / 42
see all variables and functions
       set
       displays the whole enviroment and shell functions
       (set has lots more adv uses)




             Shell Script                                  15 / 42
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                                  16 / 42
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
       see also:
           help shift
       $$ current PID, $! last background PID
       $PATH search path for programs
       $IFS input field separator




               Shell Script                       17 / 42
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 \
      eg:
           ’why don\’t you see’
      when shell reads quoted text: removes one layer of quotes!
      eg:
           X=”hello world”; touch $X; # touches hello and world
           touch ”$X”; # works.


            Shell Script                                           18 / 42
process substitution
       NOT the same as a pipe!
       ‘somecommand args‘ makes output of cmd available as
       argument
       eg:
            cat ‘ls -l‘
            ls -l | echo # fails: echo doesn’t read stdin
            x=‘pwd‘; echo $x # works: echo needs complete command line
       see also:
            xargs, $()




            Shell Script                                                 19 / 42
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
       eg:
            /usr/{bin,sbin}/vi
            {,/usr}/bin/ls




            Shell Script                                               20 / 42
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                                     21 / 42
flow control
      loops, conditionals
      instances
          conditionals
          for loop
          while loop
          until loop
          case select
          loop control
          exiting a shell




           Shell Script     22 / 42
conditionals
       if condition; then something; else something; fi
       condition is cmd, exit code governs conditional
       often used together with test builtin




            Shell Script                                 23 / 42
for loop
       for varname in list; do something; done
       assigns varname tokens from list in turn




            Shell Script                          24 / 42
while loop
       while condition; do something; done
       condition is cmd with exit code
       exit code 0 means true




             Shell Script                    25 / 42
until loop
       like while but runs until condition is true




             Shell Script                            26 / 42
exiting a shell
       exit value
       terminates the current shell, returns value to parent
       generally 0 means true, everything else false




            Shell Script                                       27 / 42
loop control
       break terminates innermost loop
       continue goes to next iteration of innermost loop




            Shell Script                                   28 / 42
case select
       like C case statement
       case ”$var” in ”$cond” ) cmd; cmd; ;; ”$cond”.... ;; esac
       details in the Scripting Guide




              Shell Script                                         29 / 42
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                              30 / 42
alternative conditionals
       using the binary logic operators && and ||
       eg:
           [ 2 = 4 ] && echo this is weird
           somethingbroken || echo help me!




            Shell Script                            31 / 42
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                                              32 / 42
output functions
      echo prints arguments, is builtin
      eg:
          echo ”hello world”
          echo ”this is pid $$”




           Shell Script                   33 / 42
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                34 / 42
printf
         external tool providing c-like printf(3)
         occasionally useful when output too complex for echo




              Shell Script                                      35 / 42
here documents
      special-purpose input redirection
      someprogram <<delimiter
      ...stuff...
      delimiter
      passes all the text between invocation and delimiter to
      program




            Shell Script                                        36 / 42
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                                    37 / 42
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                              38 / 42
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                                        39 / 42
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
            Y=’for i in *; do file $i; done’; eval $Y|less
      note the single quote here.




            Shell Script                                              40 / 42
i/o redirection
       is a shell feature
       programs usually do not (need to) know about this
       plumbs STDOUT to file, overwriting (>) or appending (>>)
       STDERR redirection uses 2>, general N>
       eg:
            ls > filelist; sort filelist >> otherfile; find 2>/dev/null
       plumbing STDIN from file (note: single file!)
       eg:
            fgrep pattern < infile
       duplicating streams: N>&M
       eg:
            cut -f 3 <infile >outfile 2>&1 # writes errors to outfile
       see also:
            man dup(2), bash
       <infile somecommand >outfile # ugly but ok
            Shell Script                                              41 / 42
pipes
        another form of redirection, does not involve files
        plumbs STDOUT of producer to STDIN of consumer
        eg:
            ls /usr/bin | grep ˆl | sort -r
        does not affect STDERR
        getting STDERR into pipe but not STDOUT is tricky
        eg:
            find / -type d 2>&1 >x |less # ugly but works
            find / -type d >x 2>&1 |less # FAILS!




             Shell Script                                    42 / 42

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:7
posted:11/27/2011
language:English
pages:42