Tuesday, October 09, 2012

Shell Script



    When to Script
·         Shell scripting can be applied to a wide variety of system and                  database tasks.

·         Though called "SCRIPTING" this is programming. it also called as shell programming.
   Repeated Tasks
                The first candidates for shell scripts will be manual tasks which are done on a
                regular basis.
·         Backups
·         Log Monitoring
·         Check disk Space.

    Occassional Tasks
·         Tasks which are performed rarely enough that their method, or even their need may be forgotten.
·         Periodic Business related reports
·         Offsite backups
·         Purging old data.
          
    Complex Manual tasks.
·         Checking for database locks
·         killing runaway processes
                                    These tasks may evolve into repeated tasks

   Special Tasks
                 These are tasks which would not be possible without a programming  
                  Language.

·         Storing OS Information into database.
·         High Frequency monitoring(several times a day or more)         

 
     Before You Start Scripting
    You will find shell scripting an iterative process, but it is best to have a good
      idea of  your goals when you start.

·         What are you trying to accomplish
·         what are the dependencies
·         which dependencies can we check first
·         which dependencies cannot be checked.
·         How broad will the effects of this script be
·         what happens if any step fails should the script continue or be halted.
·         what results or output do we want from the script.
·         who should be notified of the results and how
·         what cleanup should be done when the script is complete
·         what if two copies of the script get executed simultaneously

Your First Shell Script


   #!/bin/ksh
         echo Enter Your Name : `read YourName`
         echo Your Name is $YourName
         #end of script

    Output:

        Enter Your Name :Chandra
        Your Name is Chandra



Environment

·         The exact behavior of commands issued in the shell depends upon the execution environment provided by the shell.
·         The Unix shell maintains a set of environment variables that are used to provide information, like the current working directory, and the type of terminal being used, to the programs you run. The
·         environment variables are passed to all programs that are not built in to the shell, and may be consulted, or modified, by the program. By convention, environment variables are given in upper case letters.
·         To view all the environment variables, use the command
·         printenv
·         You can also view a particular environment variable using the echo command:
            echo $TERM
·         The above command echos the value of the TERM environment variable to the standard output.


Variables

·               Variables are set using the = sign
              Example : hello= hello
              echo $hello
·               Variables and their contents are case sensitive.
·               Shell variables are un-typed and may contain integers or text.
·               Numbers with a decimal point will be treated as text (e.g. 3.14)

        Variable Scope
·         Variables will be available within the script (or shell session) which sets them.
·         By exporting variables they can be made available to subsequently called scripts.
                export $hello
                 after setting the variable.
·         Exporting is not necessary when variables will only be used within the current script. 

       Using Variables        
·          If you are trying to use a variable where it may be surrounded by other  
          letters you may need to
·         Add curly braces {} around the name.
                                           $ echo ${hello}_hai     

        Using Arguments
      
·           The variables $1,$2,$3 etc. refer to the arguments given in order.
·           The variable $@ refers to the complete string of arguments.
·           The variable $# will give the number of arguments given.

                 Variable              Usage                                                                         
       
                         $#                     number of arguments on the command line                                 
                         $-                     options supplied to the shell                         
                         $?                     exit value of the last command executed                                   
                         $$                     process number of the current process                                         
                         $!                      process number of the last command done in background                    
                         $n                     argument on the command line, where n is from 1
                                                  through 9,  reading left to right                                                          
                         $0                     the name of the current shell or program                                      
                         $*                     all arguments on the command line ("$1 $2 ... $9")                           
                         $@                   all arguments on the command line, each separately
                                                  quoted  ("$1" "$2" ... "$9")                                                     
                         $argv[n]            selects the nth word from the input list                                         
                         ${argv[n]}        same as above                                                                  
                         $#argv              report the number of words in the input list   


         Sample Script
            #!/bin/sh
            echo "$#:" $#
            echo '$#:' $#
            echo '$-:' $-
            echo '$?:' $?
            echo '$$:' $$
            echo '$!:' $!
            echo '$3:' $3
            echo '$0:' $0
            echo '$*:' $*
            echo '$@:' $@
     Out Put
    -----------------
            $ ./variables.sh one two three four five
            5: 5
            $#: 5
            $-:
            $?: 0
            $$: 12417
            $!:
            $3: three
            $0: ./variables.sh
            $*: one two three four five
            $@: one two three four five

Important environment variables
Here are descriptions of some of the most important environment variables, and examples of how some variables can affect the execution of commands.

TERM
·         The TERM environment variable defines the type of terminal that you are using. Most Unix systems have a database of terminal types, and the capabilities of each terminal type.
PATH
·        The PATH variable contains the names of directories to be searched for programs that correspond to command names. When you issue a command to the shell, the shell searches sequentially through each directory in the PATH list until it finds an executable program with the command name you typed.
USER
·         The USER variable contains your username. Any time you access a file or directory, the access permissions are checked against the value of USER.
HOME
·         The HOME variable contains the name of your home directory. When you issue the cd command with no directory argument, you will be placed in the directory defined in the HOME environment variable. The HOME variable is also where the shell will look for the user login scripts.
MAIL
·         The MAIL variable contains the name of the directory where your incoming mail is stored.
·         When you start a mail program, the program will look in the directory stored in the MAIL environment variable for your incoming mail messages.
EDITOR
·         The EDITOR variable is used by programs that must invoke a text editor to provide the ability to edit or compose documents. One example is the elm program, which is used to read and send electronic mail. If you elect to compose a new mail message while in elm, the elm program will check the contents of the EDITOR variable to determine which editor to invoke.

HOST
·         The HOST environment variable contains the name of the host machine that is running your shell program.
·         When you connect to a remote host through telnet or ftp, the name of your host is relayed to the remote machine, so the administrators of the remote machine can keep track of who is connecting, and from where.


Setting environment and shell variables
·         The exact mechanism for setting the environment and shell variables depends upon the type of shell you're using.

                  sh, or ksh
·         To set an environment variable in sh or ksh, use the syntax VAR=value;export VAR, where VAR is the name of the environment variable and value is the value you wish to assign.
·          Do not put spaces on either side of the equals sign. The export command instructs the shell to propagate the value of the variable to all programs that are run by the shell.
·          If an environment variable is reset, but not exported, the change will only apply to the shell itself.
·         To set the EDITOR variable to the value emacs in ksh or sh, use the command:
                  EDITOR=emacs; export EDITOR
·         It is also possible to unset environment variables, with the unset command. Unsetting an environment variable removes the definition of the variable.
      csh
·         To set an environment variable in csh, use the setenv command. The command has the syntax:
               setenv VARIABLE value.
·         To set the EDITOR variable to the value emacs in csh, use the command:
                              setenv EDITOR emacs

Parameter Substitution
            $parameter                      substitute the value of parameter for this string
            ${parameter}                  same as above. The brackets are helpful if there’s no 
                                                    Separation between this parameter and a neighboring
                                                    string.
            $parameter=                    sets parameter to null.
            ${parameter-default}      if parameter is not set, then use default as the value here.
                                                    The parameter is not reset.
            ${parameter=default}     if parameter is not set, then set it to default and use the
                                                    new value
            ${parameter+newval)     if parameter is set, then use newval, otherwise use
                                                    nothing here. The parameter is not reset.
            ${parameter?message}   if parameter is not set, then display message. If
                                                    parameter is set, then use its current value




Shell Basics

Echo
  
     echo - display a line of text  

           Example:

             echo “Hello”
             echo Enter your Name:
             read  name
             echo $name
             echo “your name is $name”
             echo ‘$name’
             echo `date +%Y%m%d`
             echo ‘your name is \$name’

           Output :

Read

 Example:
   read hello
   echo $hello

           use -s if you dont whant the input to be displayed while entering
                        example: while entering password.

  Cat

     cat - concatenate files and print on the standard output
 
    Common Options

         -n     precede each line with a line number
        -v     display non-printing characters, except tabs, new-lines, and form-feeds
        -e     display $ at the end of each line (prior to new-line) (when used with -v option)


       Example

          cat file1
          cat file1 file2 file3
          cat >file1


   more, less and pg- page through a file

      more, less, and pg let you page through the contents of a file one screenful at a time.
     These may not all be available on your Unix system.
     They allow you to back up through the previous pages and search for words, etc.

Syntax
more [options] [+/pattern] [filename]
less [options] [+/pattern] [filename]
pg [options] [+/pattern] [filename]

Options
more                    less                      pg            Action
-c                            -c                        -c            clear display before displaying
                               -i                                         ignore case
-w                      default                 default      don’t exit at end of input, but prompt
                                                                          and wait
-lines                                               -lines         # of lines/screenful
+/pattern        +/pattern              +/pattern    search for the pattern
 

Internal Controls
       more                                  displays (one screen at a time) the file requested
                >              to view next screen
                or      to view one more line
                  q                                  to quit viewing the file
                  h                                  help
                 b                               go back up one screen full
                 /word                       search for word in the remainder of the file


head, tail

 head displays the head, or start, of the file.
  Syntax
         head [options] file
  Common Options
          -n           number number of lines to display, counting from the top of the file

tail displays the tail, or end, of the file.
  Syntax
       tail [options] file
Common Options
        -number      number of lines to display, counting from the bottom of the file.



single, double quotes

  Single Quotes
       
·         Single quotes will cause all special characters(except the single quote) to be
       ignored.
        
        Example
             $echo 'In single quotes "double quotes", $ and even ; are all safe'
      
  Double Quotes
       
·         Double quotes will cause most special characters to be ignored.
·         Variables and back quotes will be expanded and backslashes are interpreted as an escape character.

             $echo "In double quotes we can use variables like $hello"


Special Characters

Backslash

  • The Escape character will prevent the shell from interpreting the following character as anything  other than text.
  • Backslash(\) is the escape character in the Bash shell
  • Escaping special characters(such as * ' $ ; and space) can help you get the output
  • You  want and to handle specuil characters in file names.

             $ echo "The escape characted in Bash is \"\\\""

Shebang(#!)

·                   The "Shebang" is a special comment . since it is a comment it will not be executed when the script is run.
·                   Instead before the script is run, the shell calling the script will check for the #! pattern. if found it will invoke the script using that interpreter.

·                 IF no #! is found most shells will use the current shell to run the script.

·                   The Shells are installed in different locations on different systems you
              may have to  alter the #! line. for example, the bash shell may be in

                                /bin/bash, /usr/bin/bash or /usr/local/bin/bash
Wildcards
   Key Commands



chmod, chown

  chmod    -     change file permissions

 Each of the permission types is represented by either a numeric equivalent:
   read=4, write=2, execute=1
or a single letter:
   read=r, write=w, execute=x


     +      add permissions
     -       remove permissions
     =      set permissions

Syntax
    chmod   nnn [argument list] numeric mode
   chmod    [who]op[perm] [argument list] symbolic mode


Common Options
         -f             force (no error message is generated if the change is unsuccessful)
         -R            recursively descend through the directory structure and change the modes

Examples

If the permission desired for file1 is user: read, write, execute, group: read, execute, other: read, execute, the command to use would be
chmod 755 file1    or        chmod u=rwx,go=rx file1


chown

  chown - change ownership

   Syntax
         chown [options] user[:group]
  Common Options

             -R          recursively descend through the directory structure
             -f           force, and don’t report any errors
Examples
# chown new_owner file

cmp – Compare files
The cmp command compares two files, and (without options) reports the location of the first difference between them.
It can deal with both binary and ASCII file comparisons.
It does abyte-by-byte comparison.
Syntax

cmp [options] file1 file2 [skip1] [skip2]

The skip numbers are the number of bytes to skip in each file before starting the comparison.

Common Options
    -l                  report on each difference
    -s                 report exit status only, not byte differences

diff - differences in files

    The diff command compares two files, directories, etc, and reports all differences
    between the two.
    It deals only with ASCII files.
    It’s output format is designed to report the changes necessary to convert
    the first file into the second.
Syntax

diff [options] file1 file2

Common Options
             -b                 ignore trailing blanks
             -I                 ignore the case of letters
            -w                ignore and characters
            -e                 produce an output formatted for use with the editor, ed
             -r                  apply diff recursively through common sub-directories

tar - archive files
  The tar command combines files into one device or filename for archiving purposes.
  The tar command does not compress the files; it merely makes a large quantity of files
  more manageable.

Syntax
   tar [options] [directory file]
Common Options

           c             create an archive (begin writting at the start of the file)
           t             table of contents list
           x            extract from an archive
           v            verbose
           f             archive file name
           b         archive block size
tar will accept its options either with or without a preceding hyphen (-).
The archive file can be a disk file, a tape device, or standard input/output. The latter are represented by a hyphen.

uniq - remove duplicate lines

uniq filters duplicate adjacent lines from a file.
Syntax
   uniq [options] [+|-n] file [file.new]
Common Options
        -d        one copy of only the repeated lines
        -u        select only the lines not repeated
        +n        ignore the first n characters
        -s          n same as above (SVR4 only)
       -n        skip the first n fields, including any blanks ( & )
        -f         fields same as above (SVR4 only)

find - find files
  The find command will recursively search the indicated directory tree to find files 
   matching a type or pattern you specify.
   find can then list the files or execute arbitrary commands based on the results.
Syntax
       find directory [search options] [actions]
Common Options
         For the time search options the notation in days, n is:
         +n          more than n days
          n           exactly n days
         -n          less than n days

Text Processing & Regular Expressions

grep
This section provides an introduction to the use of regular expressions and grep.
The grep utility is used to search for generalized regular expressions occurring in Unix files.
Regular expressions, such as those shown above, are best specified in apostrophes (or single quotes) when specified in the grep utility.
The egrep utility provides searching capability using an extended set of
meta-characters.
The syntax of the grep utility, some of the available options, and a few examples are
shown below.
Syntax
         grep [options] regexp [file[s]]
Common Options
                -i                 ignore case
               -c                report only a count of the number of lines containing matches, not
                                  The matches themselves
               -v                invert the search, displaying only lines that do not match
               -n               display the line number along with the line on which a match was
                                  found
              -s                 work silently, reporting only the final status:
                                  0, for match(es) found
                                  1, for no matches
                                  2, for errors
              -l                  list filenames, but not lines, in which matches were found

sed (stream editor)

sed
The non-interactive, stream editor, sed, edits the input stream, line by line, making the specified changes, and sends the result to standard output.
Syntax
           sed [options] edit_command [file]

Common Options
             -e         script edit script
             -n        don’t print the default output, but only those lines specified by p or s///p
                         functions
             -f          script_file take the edit scripts from the file, script_file


cut - select parts of a line
    The cut command allows a portion of a file to be extracted for another use.

Syntax
        cut [options] file
Common Options
         -c         character_list character positions to select (first character is 1)
         -d         delimiter field delimiter (defaults to )
         -f          field_list fields to select (first field is 1)

paste - merge files
     The paste command allows two files to be combined side-by-side.
     The default delimiter between the columns in a paste is a tab, but options allow other
     delimiters to be used.

Syntax

paste [options] file1 file2

Common Options
         -d             list list of delimiting characters
         -s             concatenate lines


sort - sort file contents

  The sort command is used to order the lines of a file.
  Various options can be used to choose the order as well as the field on which a file is
   sorted.
 Without any options, the sort compares entire lines in the file and outputs them in ASCII order (numbers first, upper case letters, then lower case letters).

Syntax
      sort [options] [+pos1 [ -pos2 ]] file
Common Options
   -b           ignore leading blanks ( & ) when determining starting and
                 ending characters for the sort key
   -d          dictionary order, only letters, digits, and are significant
   -f           fold upper case to lower case
   -k          keydef sort on the defined keys (not available on all systems)
   -i           ignore non-printable characters
   -n          numeric sort
   -o          outfile output file
   -r           reverse the sort
    -t         char use char as the field separator character
    -u         unique; omit multiple copies of the same line (after the sort)
  +pos1 [-pos2] (old style) provides functionality similar to the "-k keydef" option.


tr - translate characters
The tr command translates characters from stdin to stdout.
Syntax
      tr [options] string1 [string2]

With no options the characters in string1 are translated into the characters in string2, character by character in the string arrays. The first character in string1 is translated into the first character in string2, etc.

 Common Options
       -c            complement the character set in string1
       -d           delete the characters in string1
        -s          squeeze a string of repeated characters in string1 to a single character



Running a Shell Script

  vi editor – basics
  
Common vi editor command list
For this Purpose
Use this vi Command Syntax
To insert new text
esc + i ( You have to press 'escape' key then 'i')
To save file
esc + : + w (Press 'escape' key  then 'colon' and finally 'w')
To save file with file name (save as)
esc + : + w  "filename"
To quit the vi editor
esc + : + q
To quit without saving
esc + : + q!
To save and quit vi editor
esc + : + wq
To search for specified word in forward direction
esc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as
/shri)
To continue with search 
n
To search for specified word in backward direction
esc + ?word (Press 'escape' key, type word-to-find)
To copy the line where cursor is located
esc + yy
To paste the text just deleted or copied at the cursor
esc + p
To delete entire line where cursor is located
esc + dd
To delete word from cursor position
esc + dw
To Find all occurrence of given word and Replace then globally without confirmation 
esc + :$s/word-to-find/word-to-replace/g
For. e.g. :$s/mumbai/pune/g
Here word "mumbai" is replace with "pune"

To Find all occurrence of given word and Replace then globally with confirmation
esc + :$s/word-to-find/word-to-replace/cg
To run shell command like ls, cp or date etc within vi
esc + :!shell-command

For e.g. :!pwd



Shell Programming Features

Numerical Calculations

Syntax:
expr op1 math-operator op2

Examples:
$ expr 1 + 3
$ expr 2 - 1
$ expr 10 / 2
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 6 + 3`
Note:
expr 20 %3 - Remainder read as 20 mod 3 and remainder is 2.
expr 10 \* 3 - Multiplication use \* and not * since its wild card.

For the last statement not the following points

(1) First, before expr keyword we used ` (back quote) sign not the (single quote i.e. ') sign. Back quote is generally found on the key under tilde (~) on PC keyboard OR to the above of TAB key.

(2) Second, expr is also end with ` i.e. back quote.

(3) Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum

(4) Here if you use double quote or single quote, it will NOT work
For e.g.
$ echo "expr 6 + 3" # It will print expr 6 + 3
$ echo 'expr 6 + 3' # It will print expr 6 + 3

Condition structures
 
          Conditional if

            if condition1
            then
                    command list if condition1 is true
            [elif condition2
                   then command list if condition2 is true]
            [else
                   command list if condition1 is false]
            fi

        Example

$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
Fi

      case esac

      case parameter in
              pattern1) [|pattern1a]) command list1;;
              pattern2) command list2
                              command list2a;;
              pattern3) command list3;;
                        *) ;;
      esac

Example

  $ cat > car
#
# if no vehicle name is given
# i.e. -z $1 is defined and it is NULL
#
# if no command line arg
if [ -z $1 ]
then
  rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as rental
  rental=$1
fi

case $rental in
   "car") echo "For $rental Rs.20 per k/m";;
   "van") echo "For $rental Rs.10 per k/m";;
   "jeep") echo "For $rental Rs.5 per k/m";;
   "bicycle") echo "For $rental 20 paisa per k/m";;
   *) echo "Sorry, I can not gat a $rental for you";;
esac

Loops

        



               for loop

    for { variable name } in { list }
       do
                     execute one for each item in the list until the list is
                     not finished (And repeat all statement between do and done)
    done
  

   Example

    for i in 1 2 3 4 5
  do
     echo "Welcome $i times"
  done


              While Loop

     while [ condition ]
           do
                 command1
                 command2
                 command3
                 ..
                 ....
            done

  Example
    #!/bin/sh
#
#Script to test while statement
#
#
if [ $# -eq 0 ]
then
   echo "Error - Number missing form command line argument"
   echo "Syntax : $0 number"
   echo " Use to print multiplication table for given number"
exit 1
fi
n=$1
i=1
while [ $i -le 10 ]
do
  echo "$n * $i = `expr $i \* $n`"
  i=`expr $i + 1`
done


SHIFT command

The shift command moves the current values stored in the positional parameters (command line args) to the left one position. For example, if the values of the current positional parameters are:
$1 = -f $2 = foo $3 = bar
and you executed the shift command the resulting positional parameters would be as follows:
$1 = foo $2 = bar

Example
$ vi shiftdemo.sh
echo "Current command line args are: \$1=$1, \$2=$2, \$3=$3"
shift
echo "After shift command the args are: \$1=$1, \$2=$2, \$3=$3"

 Test Command

Conditional statements are evaluated for true or false values.
 This is done with the test, or its equivalent, the [] operators.
  It the condition evaluates to true, a zero (TRUE) exit status is set, otherwise a non-zero  (FALSE) exit status is set.
 If there are no arguments a non-zero exit status is set.
The operators used by the Bourne shell conditional statements are given below.

For filenames the options to test are given with the syntax:
        -option filename

The options available for the test operator for files include:
       -r            true if it exists and is readable
      -w           true if it exists and is writable
       -x           true if it exists and is executable
      -f             true if it exists and is a regular file (or for csh, exists and is not a directory)
      -d            true if it exists and is a directory
     -h or -L    true if it exists and is a symbolic link
     -c             true if it exists and is a character special file (i.e. the special device is
                     Accessed one character at a time)
      -b           true if it exists and is a block special file (i.e. the device is accessed in blocks
                    of data)
      -p          true if it exists and is a named pipe (fifo)
      -u           true if it exists and is setuid (i.e. has the set-user-id bit set, s or S in the third
                    bit)
      -g           true if it exists and is setgid (i.e. has the set-group-id bit set, s or S in the
                    Sixth bit)
       -k          true if it exists and the sticky bit is set (a t in bit 9)
      -s            true if it exists and is greater than zero in size


There is a test for file descriptors:
       -t               [file_descriptor] true if the open file descriptor (default is 1, stdin) is   
                         associated with a terminal
 There are tests for strings:

       -z             string true if the string length is zero
       -n            string true if the string length is non-zero
       string1 = string2 true if string1 is identical to string2
       string1 != string2 true if string1 is non identical to string2
       string true if string is not NULL

There are integer comparisons:
        n1 -eq n2     true if integers n1 and n2 are equal
        n1 -ne n2     true if integers n1 and n2 are not equal
        n1 -gt n2      true if integer n1 is greater than integer n2
        n1 -ge n2     true if integer n1 is greater than or equal to integer n2
        n1 -lt n2       true if integer n1 is less than integer n2
        n1 -le n2      true if integer n1 is less than or equal to integer n2

The following logical operators are also available:
         !          negation (unary)
        -a         and (binary)
       -o or (binary)
() expressions within the () are grouped together. You may need to quote the ()
to prevent the shell from interpreting them.


Functions
Function is series of instruction/commands. Function performs particular activity in shell i.e. it had specific work to do or simply say task. To define function use following syntax:
Syntax:
           function-name ( )
           {
                command1
                command2
                .....
                ...
                commandN
                return
           }


Example

$ SayHello()
{
   echo "Hello $LOGNAME, Have nice computing"
   return

}


Advanced Scripting


/dev/null - Use to send unwanted output of program

This is special Linux file which is used to send any unwanted output from program/command.
Syntax:
command > /dev/null
Example:
$ ls > /dev/null
Setting Traps

When a program is terminated before it would normally end, we can catch an exit signal.
This is called a trap.

  Example
     trap ‘echo “\nEXITING on a TRAPPED SIGNAL”;exit’ 1 2 3 15

 Example

 ############################
function trap_exit
{
     # Tell the co-process to break out of the loop
       BREAK_OUT=’Y’
       print -p $BREAK_OUT # Use “print -p” to talk to the co-process
}
############################
function proc_watch
{
       # This function is started as a co-process!!!
           while : # Loop forever
           do
           Some Code Here
           read $BREAK_OUT # Do NOT need a “-p” to read!
             if [[ $BREAK_OUT = ‘Y’ ]]
              then
                    return 0
             fi
         done
}
############################
##### Start of Main ########
############################
### Set a Trap ###
trap ‘trap_exit; exit 2’ 1 2 3 15
TOTAL_SECONDS=300
BREAK_OUT=’N’
proc_watch |&    # Start proc_watch as a co-process!!!!
PW_PID=$1      # Process ID of the last background job
until (( TOTAL_SECONDS == 0 ))
do
          (( TOTAL_SECONDs = TOTAL_SECONDS - 1 ))
          sleep 1
done
BREAK_OUT=’Y’
# Use “print -p” to communicate with the co-process variable
print -p $BREAK_OUT
kill $PW_PID   # Kill the background co-process
exit 0

Default Values for Variables

#!/bin/bash
test=$1
: ${test:="hello"}
echo $test

: ${test:="hello"}==> this means if the variable test is not already set, set the variable to hello. You can also write same statement with following cod

if [ -z "$RSRC" ]
then
   test=”hello”
fi


Temporary Files

Various methods exists to create a random temporary file name. This is useful if your application/shell scripting needs temporary unique file names.
   Example—Method 1
   echo "List of temporary files : "
   for i  in 1 2 3 4 5
  do
      FILE="/tmp/$(basename $0).$RANDOM.txt"
     echo $FILE # show file name
      > $FILE # create files
  Done

Example—Method 2 Use of mktemp or tempfile utility
  $ mktemp

   Output:
/tmp/tmp.IAnO5O

$ tempfile

  Output:
/tmp/IAnO5O

Make a unique temporary directory instead of a file using –d option to both of them

$ mktemp –d
$ tempfile –d

Both mktemp or tempfile provides the shell scripts facility to use temporary files in safe manner hence it is highly recommended to use them.

Embedding SQL in shell script
  
·        SQL* Plus command cam be called from shell script like any other command
·        The –s option can be used to suppress SQL*Plus banner command.
·        The shell will Interpret everything that follows < 
as input to sqlplus until
        It encounters another eof on its own line
·        Multiple eof i.e, file markers like eof1,eof2, can be used within same script but they need to be unique

        

Example -1 Getting value into a varaible
 #!/bin/sh
 Var=”hello”
VAR1=`sqlplus -s username/password  <
set pagesize 0 feedback off ver off heading off echo off
select  sysdate, $var from dual;
exit;
end`
echo “system date is ” $VAR1
#end of shell script

Example – 2 redirecting output to a file
#!/bin/sh
 tempfile=”/temp/temp1.bat”
`sqlplus -s username/password  < $tempfile
set pagesize 0 feedback off ver off heading off echo off
select  sysdate, $var from dual;
exit;
end`
cat $tempfile
#end of shell script