Shell Script Programs

  • Upload
    suman86

  • View
    240

  • Download
    2

Embed Size (px)

Citation preview

  • 7/23/2019 Shell Script Programs

    1/39

    # Q1.Script to sum two nos#

    #!/bin/bashif [ $# -ne 2 ]then

    echo "Usage - $0 x y"echo " Where x and y are two nos for which I will print sum"exit 1

    fiecho "Sum of $1 and $2 is `expr $1 + $2`"

    Q2. Script to find out biggest number.## Algo:# 1) START: Take three nos as n1, n2, n3.# 2) Is n1 is greater than n2 and n3, if yes# print n1 is biggest no goto step 5, otherwise goto next step# 3) Is n2 is greater than n1 and n3, if yes# print n2 is biggest no goto step 5, otherwise goto next step# 4) Is n3 is greater than n1 and n2, if yes# print n3 is biggest no goto step 5, otherwise goto next step# 5) END###!/bin/bash

    if [ $# -ne 3 ]then

    echo "$0: number1 number2 number3 are not given" >&2exit 1

    fin1=$1

    n2=$2n3=$3if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]then

    echo "$n1 is Biggest number"elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]then

    echo "$n2 is Biggest number"elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]then

    echo "$n3 is Biggest number"elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]then

    echo "All the three numbers are equal"else

    echo "I cannot figure out which number is bigger"fi

    Q3 Write script to print nos as 5,4,3,2,1 using while loop.

    # Algo:# 1) START: set value of i to 5 (since we want to start from 5, if you

  • 7/23/2019 Shell Script Programs

    2/39

    # want to start from other value put that value)# 2) Start While Loop# 3) Chick, Is value of i is zero, If yes goto step 5 else# continue with next step# 4) print i, decrement i by 1 (i.e. i=i-1 to goto zero) and# goto step 3# 5) END##!/bin/bash

    i=5

    while test $i != 0do

    echo "$i"

    i=`expr $i - 1`done

    Q.4. Write Script, using case statement to perform basic math operation as follows .

    + addition

    - subtractionx multiplication

    / division

    The name of script must be 'q4' which works as follows

    $ ./q4 20 / 3, Also check for sufficient command line arguments.

    Ans:#!/bin/bashif test $# = 3then

    case $2 in+) let z=$1+$3;;

    -) let z=$1-$3;;/) let z=$1/$3;;x|X) let z=$1*$3;;*) echo Warning - $2 invalid operator, only +,-, x, / operators allowed

    exit;;esacecho Answer is $z

    elseecho "Usage - $0 value1 operator value2"echo " Where, value1 and value2 are numeric values"echo " operator can be +,-,/,x (For Multiplication)"

    fi

    Q.5.Write a shell script to see current date, time, username, and current directory.

    #!/bin/bashecho "Hello, $LOGNAME"echo "Current date is `date`"echo "User is `who i am`"echo "Current direcotry `pwd`"

  • 7/23/2019 Shell Script Programs

    3/39

    Q.6. Write script to print given number in reverse order, for e.g. If no is 123 it must print as 321.

    # Script to reverse given no## Algo:# 1) Input number n# 2) Set rev=0, sd=0# 3) Find single digit in sd as n % 10 it will give (left most digit)# 4) Construct revrse no as rev * 10 + sd# 5) Decrment n by 1# 6) Is n is greater than zero, if yes goto step 3, otherwise next step# 7) Print rev##!/bin/bashif [ $# -ne 1 ]then

    echo "Usage: $0 number"echo " I will find reverse of given number"echo " For eg. $0 123, I will print 321"exit 1

    fi

    n=$1

    rev=0sd=0

    while [ $n -gt 0 ]do

    sd=`expr $n % 10`rev=`expr $rev \* 10 + $sd`n=`expr $n / 10`

    doneecho "Reverse number is $rev"

    Q.7.Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all digit will

    be 1+2+3 = 6.

    #!/bin/bash

    # Algo:# 1) Input number n# 2) Set sum=0, sd=0# 3) Find single digit in sd as n % 10 it will give (left most digit)# 4) Construct sum no as sum= sum + sd# 5) Decrment n by 1

    # 6) Is n is greater than zero, if yes goto step 3, otherwise next step# 7) Print sum#if [ $# -ne 1 ]then

    echo "Usage: $0 number"echo " I will find sum of all digit for given number"echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"exit 1

    fi

    n=$1sum=0

  • 7/23/2019 Shell Script Programs

    4/39

    sd=0while [ $n -gt 0 ]do

    sd=`expr $n % 10`sum=`expr $sum + $sd`n=`expr $n / 10`

    doneecho "Sum of digit for number is $sum"

    Q.8.How to perform real number (number with decimal point) calculation in Linux.

    Answer: Use Linux's bc command

    Q.9.How to calculate 5.12 + 2.5 real number calculation at $ prompt in Shell ?

    Answer: Use command as , $ echo 5.12 + 2.5 | bc ,here we are giving echo commands output to bc to calculate the 5.12 + 2.5

    Q.10.How to perform real number calculation in shell script and store result tothird variable, lets say a=5.66, b=8.67, c= a+b?

    #a=5.66b=8.67c=`echo $a + $b | bc`echo "$a + $b = $c"

    Q.11.Write script to determine whether given file exist or not, file name is supplied ascommand line argument, also check for sufficient number of command line argument.

    if [ $# -ne 1 ]then

    echo "Usage - $0 file-name"exit 1

    fi

    if [ -f $1 ]then

    echo "$1 file exist"else

    echo "Sorry, $1 file does not exist"fi

    Q.12.Write script to determine whether given command line argument ($1) contains "*"symbol or not, if $1 does not contains "*" symbol add it to $1, otherwise show message"Symbol is not required". For e.g. If we called this script Q12 then after giving,

    $ Q12 /binHere $1 is /bin, it should check whether "*" symbol is present or not if not it shouldprint Required i.e. /bin/*, and if symbol present then Symbol is not required must beprinted. Test your script as$ Q12 /bin$ Q12 /bin/*

    #!/bin/bash# Script to check whether "/*" is included, in $1 or not

    cat "$1" > /tmp/file.$$ 2>/tmp/file0.$$

  • 7/23/2019 Shell Script Programs

    5/39

    grep "*" /tmp/file.$$ >/tmp/file0.$$

    if [ $? -eq 1 ]then

    echo "Required i.e. $1/*"else

    echo "Symbol is Not required"fi

    rm -f /tmp/file.$$rm -f /tmp/file0.$$

    Q.13. Write script to print contains of file from given line number to next given numberof lines. For e.g. If we called this script as Q13 and run as$ Q13 5 5 myfile , Here print contains of 'myfile' file from line number 5 to next 5 lineof that file.

    #!/bin/bash# Shell script to print contains of file from given line no to next given number lines

    # Print error / diagnostic for user if no arg's given#if [ $# -eq 0 ]then

    echo "$0:Error command arguments missing!"echo "Usage: $0 start_line uptoline filename"echo "Where start_line is line number from which you would like to print file"echo "uptoline is line number upto which would like to print"echo "For eg. $0 5 5 myfile"echo "Here from myfile total 5 lines printed starting from line no. 5 to"echo "line no 10."exit 1

    fi

    ## Look for sufficent arg's#

    if [ $# -eq 3 ]; thenif [ -e $3 ]; then

    tail +$1 $3 | head -n$2else

    echo "$0: Error opening file $3"exit 2

    fielse

    echo "Missing arguments!"fi

    Q.14. Write script to implement getopts statement, your script should understandfollowing command line argument called this script Q14,Q14 -c -d -m -eWhere options work as-c clear the screen-d show list of files in current working directory-m start mc (midnight commander shell) , if installed-e { editor } start this { editor } if installed

  • 7/23/2019 Shell Script Programs

    6/39

    #!/bin/bash# -c clear# -d dir# -m mc# -e vi { editor }#

    ## Function to clear the screen

    #cls(){

    clearecho "Clear screen, press a key . . ."readreturn

    }

    ## Function to show files in current directory#show_ls()

    { lsecho "list files, press a key . . ."readreturn

    }

    ## Function to start mc#start_mc(){

    if which mc > /dev/null ; thenmc

    echo "Midnight commander, Press a key . . ."read

    elseecho "Error: Midnight commander not installed, Press a key . . ."read

    fireturn

    }

    ## Function to start editor#start_ed()

    {ced=$1if which $ced > /dev/null ; then

    $cedecho "$ced, Press a key . . ."read

    elseecho "Error: $ced is not installed or no such editor exist, Press a key . . ."read

    fireturn

    }

  • 7/23/2019 Shell Script Programs

    7/39

    ## Function to print help#print_help_uu(){

    echo "Usage: $0 -c -d -m -v {editor name}";echo "Where -c clear the screen";echo " -d show dir";echo " -m start midnight commander shell";echo " -e {editor}, start {editor} of your choice";

    return}

    ## Main procedure start here## Check for sufficent args#

    if [ $# -eq 0 ] ; thenprint_help_uuexit 1

    fi

    ## Now parse command line arguments#while getopts cdme: optdo

    case "$opt" inc) cls;;d) show_ls;;m) start_mc;;e) thised="$OPTARG"; start_ed $thised ;;\?) print_help_uu; exit 1;;

    esacdone

    Q.15. Write script called say Hello, put this script into your startup file called .bashprofile, the script should run as soon as you logon to system, and it print any one ofthe following message in info box using dialog utility, if installed in your system, Ifdialog utility is not installed then use echo statement to print message: -Good MorningGood AfternoonGood Evening, according to system time.

    #!/bin/bash

    temph=`date | cut -c12-13`dat=`date +"%A %d in %B of %Y (%r)"`

    if [ $temph -lt 12 ]then

    mess="Good Morning $LOGNAME, Have nice day!"fi

    if [ $temph -gt 12 -a $temph -le 16 ]then

    mess="Good Afternoon $LOGNAME"fi

  • 7/23/2019 Shell Script Programs

    8/39

    if [ $temph -gt 16 -a $temph -le 18 ]then

    mess="Good Evening $LOGNAME"fi

    if which dialog > /dev/nullthen

    dialog --backtitle "Linux Shell Script Tutorial"\--title "(-: Welcome to Linux :-)"\--infobox "\n$mess\nThis is $dat" 6 60

    echo -n " Press a key to continue. . ."

    readclear

    elseecho -e "$mess\nThis is $dat"

    fi

    Q.16. How to write script, that will print, Message "Hello World" , in Bold and Blinkeffect, and in different colors like red, brown etc using echo command.

    #!/bin/bash# echo command with escape sequence to give different effects## Syntax: echo -e "escape-code your message, var1, var2 etc"# For eg. echo -e "\033[1m Hello World"# | |# | |# Escape code Message#

    clearecho -e "\033[1m Hello World"# bold effectecho -e "\033[5m Blink"

    # blink effectecho -e "\033[0m Hello World"# back to noraml

    echo -e "\033[31m Hello World"# Red colorecho -e "\033[32m Hello World"# Green colorecho -e "\033[33m Hello World"# See remaing on screenecho -e "\033[34m Hello World"echo -e "\033[35m Hello World"echo -e "\033[36m Hello World"

    echo -e -n "\033[0m "# back to noraml

    echo -e "\033[41m Hello World"echo -e "\033[42m Hello World"echo -e "\033[43m Hello World"echo -e "\033[44m Hello World"echo -e "\033[45m Hello World"echo -e "\033[46m Hello World"

    echo -e "\033[0m Hello World"

  • 7/23/2019 Shell Script Programs

    9/39

    # back to noraml

    Q.17. Write script to implement background process that will continually print currenttime in upper right corner of the screen , while user can do his/her normal job at $prompt.

    #!/bin/bash# To run type at $ promot as# $ q17 &

    #

    echoecho "Digital Clock for Linux"echo "To stop this clock use command kill pid, see above for pid"echo "Press a key to continue. . ."

    while :do

    ti=`date +"%r"`echo -e -n "\033[7s" #save current screen postion & attributes## Show the clock

    #tput cup 0 69 # row 0 and column 69 is used to show clock

    echo -n $ti # put clock on screen

    echo -e -n "\033[8u" #restore current screen postion & attributs##Delay fro 1 second#sleep 1

    done

    Q.18. Write shell script to implement menus using dialog utility. Menu-items and actionaccording to select menu-item is as follows:

    Menu-Item Purpose Action for Menu-Item

    Date/time To see current date timeDate and time must be shown using infobox of dialogutility

    Calendar To see current calendar Calendar must be shown using infobox of dialog utility

    Delete To delete selected file

    First ask user name of directory where all files are

    present, if no name of directory given assumes currendirectory, then show all files only of that directory, Filemust be shown on screen using menus of dialog utilitylet the user select the file, then ask the confirmation tuser whether he/she wants to delete selected file, ifanswer is yes then delete the file , report errors if anwhile deleting file to user.

    Exit To Exit this shell script Exit/Stops the menu driven program i.e. this script

    Note: Create function for all action for e.g. To show date/time on screen create functionshow_datetime().

  • 7/23/2019 Shell Script Programs

    10/39

    #!/bin/bash

    show_datetime(){

    dialog --backtitle "Linux Shell Tutorial" --title "System date and Time" --infobox"Date is `date`" 3 40

    readreturn

    }

    show_cal(){

    cal > menuchoice.temp.$$dialog --backtitle "Linux Shell Tutorial" --title "Calender" --infobox "`cat

    menuchoice.temp.$$`" 9 25readrm -f menuchoice.temp.$$return

    }

    delete_file(){dialog --backtitle "Linux Shell Tutorial" --title "Delete file"\

    --inputbox "Enter directory path (Enter for Current Directory)"\10 40 2>/tmp/dirip.$$rtval=$?case $rtval in

    1) rm -f /tmp/dirip.$$ ; return ;;255) rm -f /tmp/dirip.$$ ; return ;;

    esacmfile=`cat /tmp/dirip.$$`if [ -z $mfile ]then

    mfile=`pwd`/*

    elsegrep "*" /tmp/dirip.$$if [ $? -eq 1 ]then

    mfile=$mfile/*fi

    fifor i in $mfiledo

    if [ -f $i ]then

    echo "$i Delete?" >> /tmp/finallist.$$

    fidone

    dialog --backtitle "Linux Shell Tutorial" --title "Select File to Delete"\--menu "Use [Up][Down] to move, [Enter] to select file"\20 60 12 `cat /tmp/finallist.$$` 2>/tmp/file2delete.tmp.$$rtval=$?

    file2erase=`cat /tmp/file2delete.tmp.$$`case $rtval in

  • 7/23/2019 Shell Script Programs

    11/39

    0) dialog --backtitle "Linux Shell Tutorial" --title "Are you shur"\--yesno "\n\nDo you want to delete : $file2erase " 10 60

    if [ $? -eq 0 ] ; thenrm -f $file2eraseif [ $? -eq 0 ] ; then

    dialog --backtitle "Linux Shell Tutorial"\--title "Information: Delete Command" --infobox "File: $file2erase is

    Sucessfully deleted,Press a key" 5 60read

    elsedialog --backtitle "Linux Shell Tutorial"\--title "Error: Delete Command" --infobox "Error deleting File: $file2erase,

    Press a key" 5 60readfi

    elsedialog --backtitle "Linux Shell Tutorial"\--title "Information: Delete Command" --infobox "File: $file2erase is not

    deleted, Action is canceled, Press a key" 5 60read

    fi;;

    1) rm -f /tmp/dirip.$$ ; rm -f /tmp/finallist.$$ ;rm -f /tmp/file2delete.tmp.$$; return;;255) rm -f /tmp/dirip.$$ ; rm -f /tmp/finallist.$$ ;

    rm -f /tmp/file2delete.tmp.$$; return;;esacrm -f /tmp/dirip.$$rm -f /tmp/finallist.$$rm -f /tmp/file2delete.tmp.$$return}

    while true

    dodialog --clear --title "Main Menu" \

    --menu "To move [UP/DOWN] arrow keys \n\[Enter] to Select\n\

    Choose the Service you like:" 20 51 4 \"Date/time" "To see System Date & Time" \"Calender" "To see Calaender"\"Delete" "To remove file"\"Exit" "To exit this Program" 2> menuchoice.temp.$$

    retopt=$?

    choice=`cat menuchoice.temp.$$`

    rm -f menuchoice.temp.$$

    case $retopt in0)

    case $choice inDate/time) show_datetime ;;Calender) show_cal ;;Delete) delete_file ;;Exit) exit 0;;

    esac;;1) exit ;;

  • 7/23/2019 Shell Script Programs

    12/39

    255) exit ;;esacdoneclear

    Q.19. Write shell script to show various system configuration like1) Currently logged user and his logname2) Your current shell3) Your home directory4) Your operating system type

    5) Your current path setting6) Your current working directory7) Show Currently logged number of users8) About your os and version ,release number , kernel version9) Show all available shells10) Show mouse settings11) Show computer cpu information like processor type, speed etc12) Show memory information13) Show hard disk information like size of hard-disk, cache memory, model etc14) File system (Mounted)

    #!/bin/bash

    nouser=`who | wc -l`echo -e "User name: $USER (Login name: $LOGNAME)" >> /tmp/info.tmp.01.$$$echo -e "Current Shell: $SHELL" >> /tmp/info.tmp.01.$$$echo -e "Home Directory: $HOME" >> /tmp/info.tmp.01.$$$echo -e "Your O/s Type: $OSTYPE" >> /tmp/info.tmp.01.$$$echo -e "PATH: $PATH" >> /tmp/info.tmp.01.$$$echo -e "Current directory: `pwd`" >> /tmp/info.tmp.01.$$$echo -e "Currently Logged: $nouser user(s)" >> /tmp/info.tmp.01.$$$

    if [ -f /etc/redhat-release ]then

    echo -e "OS: `cat /etc/redhat-release`" >> /tmp/info.tmp.01.$$$fi

    if [ -f /etc/shells ]then

    echo -e "Available Shells: " >> /tmp/info.tmp.01.$$$echo -e "`cat /etc/shells`" >> /tmp/info.tmp.01.$$$

    fiif [ -f /etc/sysconfig/mouse ]then

    echo -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$

    echo -e "Computer Mouse Information: " >> /tmp/info.tmp.01.$$$echo -e "--------------------------------------------------------------------" >>

    /tmp/info.tmp.01.$$$

    echo -e "`cat /etc/sysconfig/mouse`" >> /tmp/info.tmp.01.$$$fiecho -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$echo -e "Computer CPU Information:" >> /tmp/info.tmp.01.$$$echo -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$cat /proc/cpuinfo >> /tmp/info.tmp.01.$$$

    echo -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$echo -e "Computer Memory Information:" >> /tmp/info.tmp.01.$$$echo -e "--------------------------------------------------------------------" >>

  • 7/23/2019 Shell Script Programs

    13/39

    /tmp/info.tmp.01.$$$cat /proc/meminfo >> /tmp/info.tmp.01.$$$

    if [ -d /proc/ide/hda ]then

    echo -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$

    echo -e "Hard disk information:" >> /tmp/info.tmp.01.$$$echo -e "--------------------------------------------------------------------" >>

    /tmp/info.tmp.01.$$$

    echo -e "Model: `cat /proc/ide/hda/model` " >> /tmp/info.tmp.01.$$$echo -e "Driver: `cat /proc/ide/hda/driver` " >> /tmp/info.tmp.01.$$$echo -e "Cache size: `cat /proc/ide/hda/cache` " >> /tmp/info.tmp.01.$$$

    fiecho -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$echo -e "File System (Mount):" >> /tmp/info.tmp.01.$$$echo -e "--------------------------------------------------------------------" >>/tmp/info.tmp.01.$$$cat /proc/mounts >> /tmp/info.tmp.01.$$$

    if which dialog > /dev/nullthen

    dialog --backtitle "Linux Software Diagnostics (LSD) Shell Script Ver.1.0" --title"Press Up/Down Keys to move" --textbox /tmp/info.tmp.01.$$$ 21 70else

    cat /tmp/info.tmp.01.$$$ |morefi

    rm -f /tmp/info.tmp.01.$$$

    Q.20.Write shell script using for loop to print the following patterns on screen

  • 7/23/2019 Shell Script Programs

    14/39

    #!/bin/bash

    echo "Can you see the following:"

    for (( i=1; i

  • 7/23/2019 Shell Script Programs

    15/39

    echo "Stars"

    for (( i=1; i

  • 7/23/2019 Shell Script Programs

    16/39

    clear

    for (( i=1; i=i; s-- ))do

    echo -n " "donefor (( j=1; j

  • 7/23/2019 Shell Script Programs

    17/39

    doecho -n " "

    donefor (( j=1; j

  • 7/23/2019 Shell Script Programs

    18/39

    ## End action, if any, e.g. clean ups#END{}

    #!/bin/bash## up2low : script to convert upercase filename to lowercase in current working dir#Copy this file to your bin directory i.e. $HOME/bin as cp rename.awk $HOME/bin#

    AWK_SCRIPT="rename.awk"

    ## change your location here#awkspath=$HOME/bin/$AWK_SCRIPT

    ls -1 > /tmp/file1.$$

    tr "[A-Z]" "[a-z]" < /tmp/file1.$$ > /tmp/file2.$$

    paste /tmp/file1.$$ /tmp/file2.$$ > /tmp/tmpdb.$$

    rm -f /tmp/file1.$$rm -f /tmp/file2.$$

    ## Make sure awk script exist#

    if [ -f $awkspath ]; thenawk -f $awkspath /tmp/tmpdb.$$

    elseecho -e "\n$0: Fatal error - $awkspath not found"echo -e "\nMake sure \$awkspath is set correctly in $0 script\n"

    fi

    rm -f /tmp/tmpdb.$$

    Advance shell script

    Example cleanup: A script to clean up log files in /var/log

    # Cleanup# Run as root, of course.

    cd /var/logcat /dev/null > messagescat /dev/null > wtmpecho "Log files cleaned up."

    There is nothing unusual here, only a set of commands that could just as easily have beeninvoked one by one from the command-line on the console or in a terminal window. The

  • 7/23/2019 Shell Script Programs

    19/39

    advantages of placing the commands in a script go far beyond not having to retype them timeand again. The script becomes a program -- a tool -- and it can easily be modified or customizedfor a particular application.

    A binary comparison operator compares two variables or quantities. Note that integer and stringcomparison use a different set of operators.

    integer comparison

    -eq

    is equal to

    if [ "$a" -eq "$b" ]

    -ne

    is not equal to

    if [ "$a" -ne "$b" ]

    -gt

    is greater than

    if [ "$a" -gt "$b" ]

    -ge

    is greater than or equal to

    if [ "$a" -ge "$b" ]

    -lt

    is less than

    if [ "$a" -lt "$b" ]

    -le

    is less than or equal to

    if [ "$a" -le "$b" ]

    "$b"))

    >=

    is greater than or equal to (within double parentheses)

    (("$a" >= "$b"))

    string comparison

    =

    is equal to

    if [ "$a" = "$b" ]

    Note the whitespace framing the =.

    if [ "$a"="$b" ] is not equivalent to the above.==

    is equal to

    if [ "$a" == "$b" ]

    This is a synonym for =.

    The == comparison operator behaves differently within a double-brackets test thanwithin single brackets.

    [[ $a == z* ]] # True if $a starts with an "z" (pattern matching).[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

    [ $a == z* ] # File globbing and word splitting take place.[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).

    # Thanks, Stphane Chazelas

    !=

    is not equal to

    if [ "$a" != "$b" ]

    This operator uses pattern matching within a [[ ... ]] construct.

  • 7/23/2019 Shell Script Programs

    21/39

    is less than, in ASCII alphabetical order

    if [[ "$a" < "$b" ]]

    if [ "$a" \< "$b" ]

    Note that the "" needs to be escaped within a [ ] construct.

    See for an application of this comparison operator.

    -z

    string is null, that is, has zero length

    String='' # Zero-length ("null") string variable.

    if [ -z "$String" ]thenecho "\$String is null."

    elseecho "\$String is NOT null."

    fi # $String is null.-n

    string is not null.

    The -n test requires that the string be quoted within the test brackets. Using anunquoted string with ! -z, or even just the unquoted string alone within test bracketsnormally works; however, this is an unsafe practice. Always quote a tested string.

    Example 7-5. Arithmetic and string comparisons

    #!/bin/bash

    a=4b=5

    # Here "a" and "b" can be treated either as integers or strings.# There is some blurring between the arithmetic and string comparisons,#+ since Bash variables are not strongly typed.

    # Bash permits integer operations and comparisons on variables#+ whose value consists of all-integer characters.# Caution advised, however.

    http://tldp.org/LDP/abs/html/special-chars.html#ASCIIDEFhttp://tldp.org/LDP/abs/html/special-chars.html#ASCIIDEF
  • 7/23/2019 Shell Script Programs

    22/39

    echo

    if [ "$a" -ne "$b" ]then

    echo "$a is not equal to $b"echo "(arithmetic comparison)"

    fi

    echo

    if [ "$a" != "$b" ]then

    echo "$a is not equal to $b."echo "(string comparison)"# "4" != "5"# ASCII 52 != ASCII 53

    fi

    # In this particular instance, both "-ne" and "!=" work.

    echo

    exit 0

    Example Testing whether a string is null.

    #!/bin/bash# str-test.sh: Testing null strings and unquoted strings,#+ but not strings and sealing wax, not to mention cabbages and kings . . .

    # Using if [ ... ]

    # If a string has not been initialized, it has no defined value.# This state is called "null" (not the same as zero!).

    if [ -n $string1 ] # string1 has not been declared or initialized.then

    echo "String \"string1\" is not null."else

    echo "String \"string1\" is null."fi # Wrong result.# Shows $string1 as not null, although it was not initialized.

    echo

    # Let's try it again.

    if [ -n "$string1" ] # This time, $string1 is quoted.then

    echo "String \"string1\" is not null."else

    echo "String \"string1\" is null."fi # Quote strings within test brackets!

  • 7/23/2019 Shell Script Programs

    23/39

    echo

    if [ $string1 ] # This time, $string1 stands naked.then

    echo "String \"string1\" is not null."else

    echo "String \"string1\" is null."fi # This works fine.# The [ ... ] test operator alone detects whether the string is null.# However it is good practice to quote it (if [ "$string1" ]).## As Stephane Chazelas points out,# if [ $string1 ] has one argument, "]"# if [ "$string1" ] has two arguments, the empty "$string1" and "]"

    echo

    string1=initialized

    if [ $string1 ] # Again, $string1 stands unquoted.then

    echo "String \"string1\" is not null."else

    echo "String \"string1\" is null."fi # Again, gives correct result.# Still, it is better to quote it ("$string1"), because . . .

    string1="a = b"

    if [ $string1 ] # Again, $string1 stands unquoted.thenecho "String \"string1\" is not null."

    elseecho "String \"string1\" is null."

    fi # Not quoting "$string1" now gives wrong result!

    exit 0 # Thank you, also, Florian Wisser, for the "heads-up".

    Example 7-7

    #!/bin/bash

    # zmore

    # View gzipped files with 'more' filter.

    E_NOARGS=85E_NOTFOUND=86E_NOTGZIP=87

    if [ $# -eq 0 ] # same effect as: if [ -z "$1" ]# $1 can exist, but be empty: zmore "" arg2 arg3then

  • 7/23/2019 Shell Script Programs

    24/39

    echo "Usage: `basename $0` filename" >&2# Error message to stderr.exit $E_NOARGS# Returns 85 as exit status of script (error code).

    fi

    filename=$1

    if [ ! -f "$filename" ] # Quoting $filename allows for possible spaces.then

    echo "File $filename not found!" >&2 # Error message to stderr.exit $E_NOTFOUND

    fi

    if [ ${filename##*.} != "gz" ]# Using bracket in variable substitution.then

    echo "File $1 is not a gzipped file!"exit $E_NOTGZIP

    fi

    zcat $1 | more

    # Uses the 'more' filter.# May substitute 'less' if desired.

    exit $? # Script returns exit status of pipe.# Actually "exit $?" is unnecessary, as the script will, in any case,#+ return the exit status of the last command executed.

    compound comparison

    -a

    logical and

    exp1 -a exp2 returns true if both exp1 and exp2 are true.

    -o

    logical or

    exp1 -o exp2 returns true if either exp1 or exp2 is true.

    These are similar to the Bash comparison operators && and ||, used within double brackets.

    [[ condition1 && condition2 ]]

    The -o and -a operators work with the test command or occur within single test brackets.

    if [ "$expr1" -a "$expr2" ]then

    echo "Both expr1 and expr2 are true."else

    http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETShttp://tldp.org/LDP/abs/html/testconstructs.html#TTESTREFhttp://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETShttp://tldp.org/LDP/abs/html/testconstructs.html#TTESTREF
  • 7/23/2019 Shell Script Programs

    25/39

    echo "Either expr1 or expr2 is false."fi

    [ 1 -eq 1 ] && [ -n "`echo true 1>&2`" ] # true[ 1 -eq 2 ] && [ -n "`echo true 1>&2`" ] # (no output)# ^^^^^^^ False condition. So far, everything as expected.

    # However ...

    [ 1 -eq 2 -a -n "`echo true 1>&2`" ] # true# ^^^^^^^ False condition. So, why "true" output?

    # Is it because both condition clauses within brackets evaluate?[[ 1 -eq 2 && -n "`echo true 1>&2`" ]] # (no output)# No, that's not it.

    # Apparently && and || "short-circuit" while -a and -o do not.

    In a compound test, even quoting the string variable might not suffice. [ -n "$string" -o "$a"= "$b" ] may cause an error with some versions of Bash if $string is empty. The safe way is

    to append an extra character to possibly empty variables, [ "x$string" != x -o "x$a" ="x$b" ] (the "x's" cancel out).

    Greatest common divisor

    #!/bin/bash# gcd.sh: greatest common divisor# Uses Euclid's algorithm

    # The "greatest common divisor" (gcd) of two integers

    #+ is the largest integer that will divide both, leaving no remainder.

    # Euclid's algorithm uses successive division.# In each pass,#+ dividend

  • 7/23/2019 Shell Script Programs

    26/39

    # ------------------------------------------------------

    gcd (){

    dividend=$1 # Arbitrary assignment.divisor=$2 #! It doesn't matter which of the two is larger.

    # Why not?

    remainder=1 # If an uninitialized variable is used inside#+ test brackets, an error message results.

    until [ "$remainder" -eq 0 ]do # ^^^^^^^^^^ Must be previously initialized!

    let "remainder = $dividend % $divisor"dividend=$divisor # Now repeat with 2 smallest numbers.divisor=$remainder

    done # Euclid's algorithm

    } # Last $dividend is the gcd.

    gcd $1 $2

    echo; echo "GCD of $1 and $2 = $dividend"; echo

    Example Generating random numbers

    #!/bin/bash

    # $RANDOM returns a different random integer at each invocation.# Nominal range: 0 - 32767 (signed 16-bit integer).

    MAXCOUNT=10count=1

    echoecho "$MAXCOUNT random numbers:"echo "-----------------"while [ "$count" -le $MAXCOUNT ] # Generate 10 ($MAXCOUNT) random integers.do

    number=$RANDOM

    echo $numberlet "count += 1" # Increment count.

    doneecho "-----------------"

    # If you need a random int within a certain range, use the 'modulo' operator.# This returns the remainder of a division operation.

    RANGE=500

    echo

  • 7/23/2019 Shell Script Programs

    27/39

    number=$RANDOMlet "number %= $RANGE"# ^^echo "Random number less than $RANGE --- $number"

    echo

    # If you need a random integer greater than a lower bound,#+ then set up a test to discard all numbers below that.

    FLOOR=200

    number=0 #initializewhile [ "$number" -le $FLOOR ]do

    number=$RANDOMdoneecho "Random number greater than $FLOOR --- $number"echo

    # Let's examine a simple alternative to the above loop, namely# let "number = $RANDOM + $FLOOR"# That would eliminate the while-loop and run faster.# But, there might be a problem with that. What is it?

    # Combine above two techniques to retrieve random number between two limits.number=0 #initialize

    while [ "$number" -le $FLOOR ]donumber=$RANDOMlet "number %= $RANGE" # Scales $number down within $RANGE.

    doneecho "Random number between $FLOOR and $RANGE --- $number"echo

    # Generate binary choice, that is, "true" or "false" value.BINARY=2

    T=1number=$RANDOM

    let "number %= $BINARY"# Note that let "number >>= 14" gives a better random distribution#+ (right shifts out everything except last binary digit).if [ "$number" -eq $T ]then

    echo "TRUE"else

    echo "FALSE"fi

  • 7/23/2019 Shell Script Programs

    28/39

    echo

    # Generate a toss of the dice.SPOTS=6 # Modulo 6 gives range 0 - 5.

    # Incrementing by 1 gives desired range of 1 - 6.# Thanks, Paulo Marcel Coelho Aragao, for the simplification.

    die1=0die2=0# Would it be better to just set SPOTS=7 and not add 1? Why or why not?

    # Tosses each die separately, and so gives correct odds.

    let "die1 = $RANDOM % $SPOTS +1" # Roll first one.let "die2 = $RANDOM % $SPOTS +1" # Roll second one.# Which arithmetic operation, above, has greater precedence --#+ modulo (%) or addition (+)?

    let "throw = $die1 + $die2"echo "Throw of the dice = $throw"echo

    exit 0

    Example Picking a random card from a deck

    #!/bin/bash# pick-card.sh

    # This is an example of choosing random elements of an array.

    # Pick a card, any card.

    Suites="ClubsDiamondsHeartsSpades"

    Denominations="23

    45678910

    JackQueenKingAce"

  • 7/23/2019 Shell Script Programs

    29/39

    # Note variables spread over multiple lines.

    suite=($Suites) # Read into array variable.denomination=($Denominations)

    num_suites=${#suite[*]} # Count how many elements.num_denominations=${#denomination[*]}

    echo -n "${denomination[$((RANDOM%num_denominations))]} of "echo ${suite[$((RANDOM%num_suites))]}

    # $bozo sh pick-cards.sh# Jack of Clubs

    # Thank you, "jipe," for pointing out this use of $RANDOM.exit 0

    Manipulating Strings

    Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unifiedfocus. Some are a subset ofparameter substitution, and others fall under the functionality of the UNIX exprcommand. This results in inconsistent command syntax and overlap of functionality, not to mention confusion.

    String Length

    ${#string}

    expr length $string

    These are the equivalent ofstrlen() in C.

    expr "$string" : '.*'

    stringZ=abcABC123ABCabc

    echo ${#stringZ} # 15echo `expr length $stringZ` # 15echo `expr "$stringZ" : '.*'` # 15

    Example 10-1. Inserting a blank line between paragraphs in a text file

    #!/bin/bash# paragraph-space.sh# Ver. 2.0, Reldate 05Aug08

    # Inserts a blank line between paragraphs of a single-spaced text file.# Usage: $0

  • 7/23/2019 Shell Script Programs

    30/39

    #+ terminate a paragraph. See exercises at end of script.

    while read line # For as many lines as the input file has...doecho "$line" # Output the line itself.

    len=${#line}if [[ "$len" -lt "$MINLEN" && "$line" =~ \[*\.\] ]]then echo # Add a blank line immediately

    fi #+ after short line terminated by a period.

    done

    exit

    # Exercises:# ---------# 1) The script usually inserts a blank line at the end#+ of the target file. Fix this.# 2) Line 17 only considers periods as sentence terminators.# Modify this to include other common end-of-sentence characters,#+ such as ?, !, and ".

    Length of Matching Substring at Beginning of String

    expr match "$string" '$substring'

    $substring is a regular expression.

    expr "$string" : '$substring'

    $substring is a regular expression.

    stringZ=abcABC123ABCabc# |------|

    # 12345678

    echo `expr match "$stringZ" 'abc[A-Z]*.2'` # 8echo `expr "$stringZ" : 'abc[A-Z]*.2'` # 8

    Index

    expr index $string $substring

    Numerical position in $string of first character in $substring that matches.

    stringZ=abcABC123ABCabc# 123456 ...echo `expr index "$stringZ" C12` # 6

    # C position.

    echo `expr index "$stringZ" 1c` # 3# 'c' (in #3 position) matches before '1'.

    This is the near equivalent ofstrchr() in C.

    Substring Extraction

    http://tldp.org/LDP/abs/html/regexp.html#REGEXREFhttp://tldp.org/LDP/abs/html/regexp.html#REGEXREF
  • 7/23/2019 Shell Script Programs

    31/39

    ${string:position}

    Extracts substring from $stringat $position.

    If the $string parameter is "*" or "@", then this extracts thepositional parameters, [1]starting at

    $position.

    ${string:position:length}

    Extracts $length characters of substring from $stringat $position.

    stringZ=abcABC123ABCabc# 0123456789.....# 0-based indexing.

    echo ${stringZ:0} # abcABC123ABCabcecho ${stringZ:1} # bcABC123ABCabcecho ${stringZ:7} # 23ABCabc

    echo ${stringZ:7:3} # 23A

    # Three characters of substring.

    # Is it possible to index from the right end of the string?echo ${stringZ:-4} # abcABC123ABCabc# Defaults to full string, as in ${parameter:-default}.# However . . .

    echo ${stringZ:(-4)} # Cabcecho ${stringZ: -4} # Cabc# Now, it works.# Parentheses or added space "escape" the position parameter.

    # Thank you, Dan Jacobson, for pointing this out.

    The position and length arguments can be "parameterized," that is, represented as a variable, rather thanas a numerical constant.

    Example 10-2. Generating an 8-character "random" string

    #!/bin/bash# rand-string.sh# Generating an 8-character "random" string.

    if [ -n "$1" ] # If command-line argument present,then #+ then set start-string to it.str0="$1"

    else # Else use PID of script as start-string.str0="$$"

    fi

    POS=2 # Starting from position 2 in the string.LEN=8 # Extract eight characters.

    str1=$( echo "$str0" | md5sum | md5sum )# Doubly scramble ^^^^^^ ^^^^^^#+ by piping and repiping to md5sum.

    http://tldp.org/LDP/abs/html/internalvariables.html#POSPARAMREFhttp://tldp.org/LDP/abs/html/string-manipulation.html#FTN.AEN5950http://tldp.org/LDP/abs/html/string-manipulation.html#FTN.AEN5950http://tldp.org/LDP/abs/html/internalvariables.html#POSPARAMREFhttp://tldp.org/LDP/abs/html/string-manipulation.html#FTN.AEN5950
  • 7/23/2019 Shell Script Programs

    32/39

    randstring="${str1:$POS:$LEN}"# Can parameterize ^^^^ ^^^^

    echo "$randstring"

    exit $?

    # bozo$ ./rand-string.sh my-password# 1bdd88c4

    # No, this is is not recommended#+ as a method of generating hack-proof passwords.

    If the $string parameter is "*" or "@", then this extracts a maximum of$length positional parameters,

    starting at $position.

    echo ${*:2} # Echoes second and following positional parameters.echo ${@:2} # Same as above.

    echo ${*:2:3} # Echoes three positional parameters, starting at second.

    expr substr $string $position $length

    Extracts $length characters from $string starting at $position.

    stringZ=abcABC123ABCabc# 123456789......# 1-based indexing.

    echo `expr substr $stringZ 1 2` # abecho `expr substr $stringZ 4 3` # ABC

    expr match "$string" '\($substring\)'

    Extracts $substringat beginning of$string, where $substring is aregular expression.

    expr "$string" : '\($substring\)'

    Extracts $substringat beginning of$string, where $substring is a regular expression.

    stringZ=abcABC123ABCabc# =======

    echo `expr match "$stringZ" '\(.[b-c]*[A-Z]..[0-9]\)'` # abcABC1echo `expr "$stringZ" : '\(.[b-c]*[A-Z]..[0-9]\)'` # abcABC1echo `expr "$stringZ" : '\(.......\)'` # abcABC1# All of the above forms give an identical result.

    expr match "$string" '.*\($substring\)'

    Extracts $substringat endof$string, where $substring is a regular expression.

    expr "$string" : '.*\($substring\)'

    Extracts $substringat endof$string, where $substring is a regular expression.

    stringZ=abcABC123ABCabc# ======

    http://tldp.org/LDP/abs/html/regexp.html#REGEXREFhttp://tldp.org/LDP/abs/html/regexp.html#REGEXREFhttp://tldp.org/LDP/abs/html/regexp.html#REGEXREF
  • 7/23/2019 Shell Script Programs

    33/39

    echo `expr match "$stringZ" '.*\([A-C][A-C][A-C][a-c]*\)'` # ABCabcecho `expr "$stringZ" : '.*\(......\)'` # ABCabc

    Substring Removal

    ${string#substring}

    Deletes shortest match of$substring from frontof$string.

    ${string##substring}

    Deletes longest match of$substring from frontof$string.

    stringZ=abcABC123ABCabc# |----| shortest# |----------| longest

    echo ${stringZ#a*C} # 123ABCabc# Strip out shortest match between 'a' and 'C'.

    echo ${stringZ##a*C} # abc# Strip out longest match between 'a' and 'C'.

    # You can parameterize the substrings.

    X='a*C'

    echo ${stringZ#$X} # 123ABCabcecho ${stringZ##$X} # abc

    # As above.

    ${string%substring}

    Deletes shortest match of$substring from backof$string.

    For example:

    # Rename all filenames in $PWD with "TXT" suffix to a "txt" suffix.# For example, "file1.TXT" becomes "file1.txt" . . .

    SUFF=TXTsuff=txt

    for i in $(ls *.$SUFF)domv -f $i ${i%.$SUFF}.$suff# Leave unchanged everything *except* the shortest pattern match#+ starting from the right-hand-side of the variable $i . . .

    done ### This could be condensed into a "one-liner" if desired.

    # Thank you, Rory Winston.

    ${string%%substring}

    Deletes longest match of$substring from backof$string.

  • 7/23/2019 Shell Script Programs

    34/39

    stringZ=abcABC123ABCabc# || shortest# |------------| longest

    echo ${stringZ%b*c} # abcABC123ABCa# Strip out shortest match between 'b' and 'c', from back of $stringZ.

    echo ${stringZ%%b*c} # a# Strip out longest match between 'b' and 'c', from back of $stringZ.

    This operator is useful for generating filenames.

    Example Using tail to monitor the system log

    #!/bin/bash

    filename=sys.log

    cat /dev/null > $filename; echo "Creating / cleaning out file."# Creates the file if it does not already exist,#+ and truncates it to zero length if it does.

    # : > filename and > filename also work.

    tail /var/log/messages > $filename# /var/log/messages must have world read permission for this to work.

    echo "$filename contains tail end of system log."

    exit 0

    To list a specific line of a text file, pipe the output of head to tail -n 1. For examplehead -n 8 database.txt | tail -n 1 lists the 8th line of the file database.txt.

    To set a variable to a given block of a text file:

    var=$(head -n $m $filename | tail -n $n)

    # filename = name of file# m = from beginning of file, number of lines to end of block# n = number of lines to set variable to (trim from end of block)

    Newer implementations of tail deprecate the older tail -$LINES filename usage. Thestandard tail -n $LINES filename is correct.

    See also Example 16-5, Example 16-39 and Example 32-6.

    grep

    A multi-purpose file search tool that uses Regular Expressions. It was originally acommand/filter in the venerable ed line editor: g/re/p -- global - regular expression - print.

    grep pattern [file...]

    Search the target file(s) for occurrences of pattern, where pattern may be literal text or aRegular Expression.

    http://tldp.org/LDP/abs/html/special-chars.html#PIPEREFhttp://tldp.org/LDP/abs/html/moreadv.html#EX41http://tldp.org/LDP/abs/html/filearchiv.html#EX52http://tldp.org/LDP/abs/html/debugging.html#ONLINEhttp://tldp.org/LDP/abs/html/regexp.html#REGEXREFhttp://tldp.org/LDP/abs/html/special-chars.html#PIPEREFhttp://tldp.org/LDP/abs/html/moreadv.html#EX41http://tldp.org/LDP/abs/html/filearchiv.html#EX52http://tldp.org/LDP/abs/html/debugging.html#ONLINEhttp://tldp.org/LDP/abs/html/regexp.html#REGEXREF
  • 7/23/2019 Shell Script Programs

    35/39

    bash$ grep '[rst]ystem.$' osinfo.txtThe GPL governs the distribution of the Linux operating system.

    If no target file(s) specified, grep works as a filter on stdout, as in a pipe.

    bash$ ps ax | grep clock765 tty1 S 0:00 xclock901 pts/1 S 0:00 grep clock

    The -i option causes a case-insensitive search.

    The -w option matches only whole words.

    The -l option lists only the files in which matches were found, but not the matching lines.

    The -r (recursive) option searches files in the current working directory and allsubdirectories below it.

    The -n option lists the matching lines, together with line numbers.

    bash$ grep -n Linux osinfo.txt2:This is a file containing information about Linux.6:The GPL governs the distribution of the Linux operating system.

    The -v (or --invert-match) option filters out matches.

    grep pattern1 *.txt | grep -v pattern2

    # Matches all lines in "*.txt" files containing "pattern1",# but ***not*** "pattern2".

    The -c (--count) option gives a numerical count of matches, rather than actually listing thematches.

    grep -c txt *.sgml # (number of occurrences of "txt" in "*.sgml" files)

    # grep -cz .# ^ dot# means count (-c) zero-separated (-z) items matching "."# that is, non-empty ones (containing at least 1 character).#printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -cz . # 3printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -cz '$' # 5printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -cz '^' # 5#printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep -c '$' # 9# By default, newline chars (\n) separate items to match.

    # Note that the -z option is GNU "grep" specific.

    http://tldp.org/LDP/abs/html/special-chars.html#PIPEREFhttp://tldp.org/LDP/abs/html/special-chars.html#PIPEREF
  • 7/23/2019 Shell Script Programs

    36/39

    # Thanks, S.C.

    The --color (or --colour) option marks the matching string in color (on the console or in anxterm window). Since grep prints out each entire line containing the matching pattern, thislets you see exactly what is being matched. See also the -o option, which shows only thematching portion of the line(s).

    Example Converting a decimal number to hexadecimal

    #!/bin/bash# hexconvert.sh: Convert a decimal number to hexadecimal.

    E_NOARGS=85 # Command-line arg missing.BASE=16 # Hexadecimal.

    if [ -z "$1" ]

    then # Need a command-line argument.echo "Usage: $0 number"exit $E_NOARGS

    fi # Exercise: add argument validity checking.

    hexcvt (){if [ -z "$1" ]thenecho 0return # "Return" 0 if no arg passed to function.

    fi

    echo ""$1" "$BASE" o p" | dc# o sets radix (numerical base) of output.# p prints the top of stack.# For other options: 'man dc' ...return}

    hexcvt "$1"

    exit

    Example Factoring

    #!/bin/bash# factr.sh: Factor a number

    MIN=2 # Will not work for number smaller than this.E_NOARGS=85E_TOOSMALL=86

  • 7/23/2019 Shell Script Programs

    37/39

    if [ -z $1 ]thenecho "Usage: $0 number"exit $E_NOARGS

    fi

    if [ "$1" -lt "$MIN" ]thenecho "Number to factor must be $MIN or greater."exit $E_TOOSMALL

    fi

    # Exercise: Add type checking (to reject non-integer arg).

    echo "Factors of $1:"# -------------------------------------------------------echo "$1[p]s2[lip/dli%0=1dvsr]s12sid2%0=13sidvsr[dli%0=\1lrli2+dsi!>.]ds.xd1

  • 7/23/2019 Shell Script Programs

    38/39

    # ^^^^^^^^^^^^# An echo-and-pipe is an easy way of passing shell parameters to awk.

    exit

    Example A script that copies itself

    #!/bin/bash# self-copy.sh

    # This script copies itself.

    file_subscript=copy

    dd if=$0 of=$0.$file_subscript 2>/dev/null# Suppress messages from dd: ^^^^^^^^^^^

    exit $?

    # A program whose only output is its own source code#+ is called a "quine" per Willard Quine.

    Example 19-8. A script that generates another script

    #!/bin/bash# generate-script.sh# Based on an idea by Albert Reiner.

    OUTFILE=generated.sh # Name of the file to generate.

    # -----------------------------------------------------------# 'Here document containing the body of the generated script.(cat

  • 7/23/2019 Shell Script Programs

    39/39

    echo "c = $c"

    exit 0EOF) > $OUTFILE# -----------------------------------------------------------

    # Quoting the 'limit string' prevents variable expansion#+ within the body of the above 'here document.'# This permits outputting literal strings in the output file.

    if [ -f "$OUTFILE" ]then

    chmod 755 $OUTFILE# Make the generated file executable.

    elseecho "Problem in creating file: \"$OUTFILE\""

    fi

    # This method can also be used for generating#+ C programs, Perl programs, Python programs, Makefiles,#+ and the like.

    exit 0