Echo colored text in a shell script?

As part of a shell script I'm working on, I want to be able to print colored (preferably red) text to the Terminal window, to provide warnings to the user.
How can I code in echoing colored text?
(I did some googling and couldn't find anything that seemed to apply to what I want to do.)
Any help would be appreciated!
Thanks in advance!

The following is a shell script that displays the terminal colors and the escape sequences used to generate them:
#!/bin/sh
# colors.esc - display the terminal colors and the escape sequences that
# generate them. "Blink" is _NOT_ shown, as it is a very
# annoying effect, and should be avoided at all costs in normal
# daily uses.
# Usage: colors.esc [12 character or less display string]
# Bob Harris
E=$(printf ' ') # escape <E>
R="${E}[0m" # reset <E>[0m
typeset dsp_str=""
typeset dsp_txt
typeset fg_text
typeset bg_text
if [[ $# != 0 ]]; then
dsp_str=$(printf "%12.12s" "$*")
fi
color=(Black Red Green Yellow Blue Magenta Cyan White)
for bg in "" 0 1 2 3 4 5 6 7 # for each background color
do
b=$bg && [[ X$b != X ]] && b="4$b;" # deal with no background color ""
echo " ------------ ----bold---- -underline-- --reverse---"
for fg in 0 1 2 3 4 5 6 7 # for each foreground color
do
f="3$fg" # setup foreground color
line=""
for a in "" 1 4 7 # for each attribute
do
[[ X$a != X ]] && a=";$a" # deal with no attribute ""
if [[ -z "$dsp_str" ]]; then
dsp_txt=$(printf "%12s" "<E>[${b}${f}${a}m") # build esc text
else
dsp_txt="$dsp_str" # use supplied text
fi
line="${line}${E}[${b}${f}${a}m${dsp_txt}${R} " # build entry
done
fg_text=$(printf "%-7s" ${color[$fg]}) # translate foreground color
bg_text=$(printf "%-9s" "Bg${color[$bg]}") # translate background color
[[ X$b = X ]] && bg_text=$(printf "%-9s" " ") # no bckgnd color
line="$bg_text $fg_text $line" # build final display line
echo "${line% }" # display the colorized line
done
done
echo " ------------ ----bold---- -underline-- --reverse---"
bg_text=$(printf "%-9s" " ")
fg_text=$(printf "%-7s" "Reset")
dsp_txt=$(printf "%12s" "<E>[0m")
line="$bg_text $fg_text $dsp_txt" # build final display line
echo "${line% }"

Similar Messages

  • Passing dialog text to a shell script command

    Hi. Newbie here. I got a good book, will learn this sooner or later.
    But right now, I got a problem I can't figure out
    I'd like to display a dialog box that requests some text. I'd then like to use that text as the variable for a shell commmand.
    Let's say for instance that I want to prompt for the asset tag number of the machine and want the result to end up in the ARD Info 1 field. I've got the first and third line, just don't know how to "place" the captured text:
    display dialog "What is this Mac's assett tag number?" default answer ""
    do shell script "defaults write /Library/Preferences/com.apple.RemoteDesktop Text1 <resultfrom_dialoghere>"
    Anyone?
    Darrin

    You use text returned of:
    dialog reply n : Reply record for the ‘display dialog’ command
    properties
    button returned (Unicode text, r/o) : name of button chosen (empty if ‘giving up after’ was supplied and dialog timed out)
    text returned (Unicode text, r/o) : text entered (present only if ‘default answer’ was supplied)
    gave up (boolean, r/o) : Did the dialog time out? (present only if ‘giving up after’ was supplied)
    ex:
    set _result to text returned of (display dialog "What is this Mac's assett tag number?" default answer "")
    do shell script "defaults write /Library/Preferences/com.apple.RemoteDesktop Text1 " & quoted form of _result

  • How to truncate text in a shell script? [SOLVED]

    Here is my shell script...
    #!/bin/bash
    case "$1" in
    artist) dcop amarok player artist ;;
    title) dcop amarok player title ;;
    esac
    I want it to send the artist and title truncated if they are more than 20 characters and with a little '...' ellipsis at the end. Can anyone help me?
    Last edited by tony5429 (2008-03-12 13:28:24)

    This might be a starting point, even though I don't know the answer: http://developer.apple.com/documentatio … 03521-SW16 (gosh what a long URL)
    edit
    wow, I was slow
    Last edited by finferflu (2008-03-11 20:52:38)

  • Shell scripts

    Hi all,
      Can any body tell me about Shall Script.
    What is Shall Script?
    How to create it?
    Give me some material/Links for this
    Definetly reward for useful answer.
    Regards,
    Mahi.

    Hai,
    A shell script is a script written for the shell, or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. Usually, shell script refers to scripts written for a Unix shell, while COMMAND.COM (DOS) and cmd.exe (Windows) command line scripts are usually called batch files, but here properties of both are discussed.
    Many shell script interpreters double as command line interface, such as the various Unix shells, Windows PowerShell or the MS-DOS COMMAND.COM. Others, such as AppleScript or the graphical Windows Script Host (WScript.exe), add scripting capability to computing environments without requiring a command line interface. Other examples of programming languages primarily intended for shell scripting include DCL and JCL.

  • Need help with shell scripting and Patching

    Hello all,
    I am a very new Oracle DBA and I just have an interview where i have been ask two questions that i have no idea of what it is
    1/ What is shell scripting and how do you do shell scripting?
    2/ What is Patching and how do you do patching?
    Can some one help to have a very good understanding of these tow questions?
    Thanks a lot

    1/ What is shell scripting and how do you do shell scripting?shell accept command from you (via keyboard) and execute them. But if you use command one by one (sequence of 'n' number of commands) , the you can store this sequence of command to text file and tell the shell to execute this text file instead of entering the commands. This is know as shell script.
    Shell script defined as:
    "Shell Script is series of command written in plain text file. Shell script is just like batch file in MS-DOS
    for example:- for taking backup, health check and doing some task Operating system level or Oracle database level we can create shell script and schedule a cron job
    2/ What is Patching and how do you do patching?for example ,in windows while using sometimes you might face an issue/error and it gives pop up error message would like to send/report this error to microsoft? microsoft will send you a fix for that. lot of fixes for errors/bugs are released as patches.( n number of patches with newer features are releases as new version)
    likewise in oracle for resolving bugs we should have to apply patch.
    patch is basically a fix for a bug/bugs. we need to use opatch utility to apply the paches.
    hope, this helps you

  • How to parse a text file and produce a dynamic shell script for linking?

    I have some mapping files, one example is like this one;
    $ cat CON_xfrm_contract_to_20080302.map
    (object mfile_c_type
    (path "file:OBSOLETE")
    (fs "file://amanos/s01/abinitio/data/prod/mfs/mfs_16way")
    (local_paths 16
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_001/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_002/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_003/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_004/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_005/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_006/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_007/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_008/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_009/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_010/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_011/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_012/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_013/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_014/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_015/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"
      "file://amanos/s01/abinitio/data/prod/mfs/parts/mfs_16way_016/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat"))In this file's content I have some exracted text files with same names under different folders;
    $ ls -lt /s01/abinitio/data/prod/mfs/parts/mfs_16way_*/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat   [
    -rw-rw-rw-   1 ab_live  abinitio 438652105 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_010/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438490410 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_016/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438219252 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_007/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438521432 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_014/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438488130 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_003/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438249547 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_002/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438312177 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_012/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 439074566 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_015/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438722261 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_004/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438742477 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_001/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438517268 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_008/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438645835 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_011/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438334994 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_006/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438470743 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_005/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438095853 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_009/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    -rw-rw-rw-   1 ab_live  abinitio 438434204 Mar  3 01:42 /s01/abinitio/data/prod/mfs/parts/mfs_16way_013/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.datI need a shell script which will produce a shell script from the content of the mapping file so that I can be able to symbolicly link these files with different names and under the same folder, like;
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_001/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat ./mfs_16way_001.CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_016/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat ./mfs_16way_016.CON_xfrm_contract_to_20080302.datI am a newbie for shell scripting, I tried several awk and sed operations but couldn't get close to this output :(
    If you guide me I will be so glad, thank you.
    ps: amanos is the name of this server.

    this is thepoint that I am stuck, I can not add the destination sym.link name to the end of each line;
    $ grep "  \"file://amanos" CON_xfrm_contract_to_20080302.map | cut -c17- | sed  's/"//;s/)//g' | sed 's/\/s01/ln -s \/s01/g'
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_001/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_002/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_003/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_004/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_005/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_006/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_007/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_008/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_009/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_010/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_011/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_012/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_013/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_014/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_015/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    ln -s /s01/abinitio/data/prod/mfs/parts/mfs_16way_016/mfs_16way/Applications/RDS/CON_PUB/main/CON_xfrm_contract_to_20080302.dat
    $ /)//g' | sed 's/\/s01/ln -s \/s01/g' | awk -F\/ '{print $8"."$14}'                                                       <
    mfs_16way_001.CON_xfrm_contract_to_20080302.dat
    mfs_16way_002.CON_xfrm_contract_to_20080302.dat
    mfs_16way_003.CON_xfrm_contract_to_20080302.dat
    mfs_16way_004.CON_xfrm_contract_to_20080302.dat
    mfs_16way_005.CON_xfrm_contract_to_20080302.dat
    mfs_16way_006.CON_xfrm_contract_to_20080302.dat
    mfs_16way_007.CON_xfrm_contract_to_20080302.dat
    mfs_16way_008.CON_xfrm_contract_to_20080302.dat
    mfs_16way_009.CON_xfrm_contract_to_20080302.dat
    mfs_16way_010.CON_xfrm_contract_to_20080302.dat
    mfs_16way_011.CON_xfrm_contract_to_20080302.dat
    mfs_16way_012.CON_xfrm_contract_to_20080302.dat
    mfs_16way_013.CON_xfrm_contract_to_20080302.dat
    mfs_16way_014.CON_xfrm_contract_to_20080302.dat
    mfs_16way_015.CON_xfrm_contract_to_20080302.dat
    mfs_16way_016.CON_xfrm_contract_to_20080302.datMessage was edited by:
    antu
    Message was edited by:
    antu

  • Shell scripts to read data from a text file and to load it into a table

    Hi All,
    I have a text file consisting of rows and columns as follows,
    GEF001 000093625 MKL002510 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL003604 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL005675 000001 000000 000000 000000 000000 000000 000001 My requirement is that, i should read the first 3 columns of this file using a shell script and then i have to insert the data into a table consisting of 3 rows in oracle .
    the whole application is deployed in unix and that text file comes from mainframe. am working in the unix side of the application and i cant access the data directly from the mainframe. so am required to write a script which reads the data from text file which is placed in certain location and i have to load it to oracle database.
    so I can't use SQL * loader.
    Please help me something with this...
    Thanks in advance.

    1. Create a dictionary object in Oracle and assign it to the folder where your file resides
    2. Write a little procedure which opens the file in the newly created directory object using ULT_FILE and inside the FOR LOOP and do INSERTs to table you want
    3. Create a shell script and call that procedure
    You can use the post in my Blog for such issues
    [Using Oracle UTL_FILE, UTL_SMTP packages and Linux Shell Scripting and Cron utility together|http://kamranagayev.wordpress.com/2009/02/23/using-oracle-utl_file-utl_smtp-packages-and-linux-shell-scripting-and-cron-utility-together-2/]
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com

  • Duplicate Text From Shell Script in Automator

    I'm trying to run a automator script that allows me to select a couple of files, run a sha1 checksum, and output a text file. My current version works 100% within the automator app, however when I use it as a context menu service, it outputs duplicate text. Here's my current workflow and what it outputs.
    Get Selected Folder Items
    Run Shell Script
    Copy to Clipboard (I've tried "new text file", and "new textedit file" as well)
    Outputs:
    SHA1(~/Desktop/Actions/Test/TEST.atn)= 88902acfb51e0f9a0c6dbedce69ce9618e26bc00
    SHA1(~/Desktop/Actions/Test/TEST.atn)= 88902acfb51e0f9a0c6dbedce69ce9618e26bc00
    Any help would be appreciated.

    Snow Leopard's Services workflow is automatically passed the type of selected items (that is what the selections at the top of workflow window are for), so just remove the *Get Selected Finder Items* action, since that is having the result of doubling the input items.

  • Tips for parsing xml in a shell script?

    Hello,
    I'm writing a shell script to extract info from an xml file to create various text files that share data in the form of custom entities declared at the top of the document (product id, name, version, copyright date, etc.). So far I'm using xmllint which is working well. I'm extracting text for my project files using xmllint --shell:
    <pre style="padding-left: .75ex; padding-top: .25em; padding-bottom: .25em; margin-top: .5em; margin-bottom: .5em; margin-left: 1ex; max-width: 80ex; overflow: auto; font-size: 10px; font-family: Monaco, 'Courier New', Courier, monospace; color: #222; background: #eee; line-height: normal">echo cat lls_cd_product/plist | xmllint --noent --shell xyz.xml | sed -e '1d; $d'</pre>
    This is working well, but --shell mode adds an extra line to the beginning and end which I let sed cleanup, but then I need to strip the enclosing tags as well.
    Xmllint does a good job of filling in my entities with the exception of MacRoman bullet characters that I've entered as &#165;. These are just converted to the same entity in hex, &#xA5;. I suppose I can replace those with sed, but that's starting to feel kludgey.
    I'm beginning to wonder if there may be a better way to do this. I'm not very familiar with XSL, but I am considering ramping up on that.
    Any suggestions would be welcome.
    Cole

    etresoft wrote:
    It may be a few hours before I get time to work on it.
    Or not.
    Here is your XML file:
    <?xml version="1.0" encoding="UTF-8"?>
    <info>
    <ver>2.1.1</ver>
    <tag>abc</tag>
    <name>Product Name</name>
    <filename>productname</filename>
    <copyright>2008</copyright>
    </info>
    This generates the cd product file:
    <?xml version="1.0"?>
    <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8"
    doctype-system="http://www.apple.com/DTDs/PropertyList-1.0.dtd"
    doctype-public="-//Apple Computer//DTD PLIST 1.0//EN"/>
    <!-- You could access addition data from some other XML file. -->
    <!-- <xsl:variable name="data" select="document('data.xml')/data"/> -->
    <xsl:template match="info">
    <plist version="1.0">
    <dict>
    <key>hfs-openfolder</key>
    <string>.</string>
    <key>hfs-volume-name</key>
    <string><xsl:value-of select="name"/></string>
    <key>hide-hfs</key>
    <string>./{Norton,*.txt,*.exe,.inf}</string>
    <key>hide-iso</key>
    <string>./{PDS,*Rename,readme,.Volume*,Norton*,*icns,Run*.app,Icon*,Desktop*,TheFolder}</string>
    <key>hide-joliet</key>
    <string>./{PDS,*Rename,readme,.Volume*,Norton*,*icns,Run*.app,Icon*,Desktop*,TheFolder}</string>
    <key>iso-volume-name</key>
    <string><xsl:value-of select="tag"/></string>
    <key>joliet-volume-name</key>
    <string><xsl:value-of select="name"/></string>
    </dict>
    </plist>
    </xsl:template>
    </xsl:stylesheet>
    and this generates the Mac read me file in XML:
    <?xml version="1.0"?>
    <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:output method="xml" indent="yes" version="1.0" encoding="UTF-8"/>
    <!-- You could access addition data from some other XML file. -->
    <!-- <xsl:variable name="data" select="document('data.xml')/data"/> -->
    <xsl:template match="info">
    <!-- You don't have to deal with these entities anymore. You should be
    able to save this xsl file in UTF-8 format and just type in the
    bullets. But the entities work too. -->
    <readme_mac><xsl:value-of select="concat(name, ' ', ver)"/>
    Copyright <xsl:value-of select="copyright"/>, Laureate Learning Systems¨, Inc.
    Minimum System Requirements:
    ¥ 300 MHz or faster PowerPC, Intel or better CPU
    ¥ Mac OS 8.1 or later, including any Mac OS X
    ¥ 64 MB available RAM
    ¥ 60 MB available disk space
    </readme_mac>
    </xsl:template>
    </xsl:stylesheet>
    This one will output the readme in HTML:
    <?xml version="1.0"?>
    <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:output method="html" indent="yes" version="4.0" encoding="UTF-8"/>
    <!-- You could access addition data from some other XML file. -->
    <!-- <xsl:variable name="data" select="document('data.xml')/data"/> -->
    <xsl:template match="info">
    <!-- You don't have to deal with these entities anymore. You should be
    able to save this xsl file in UTF-8 format and just type in the
    bullets. But the entities work too. -->
    <html>
    <head>
    <title><xsl:value-of select="concat(name, ' ', ver)"/></title>
    </head>
    <body>
    <xsl:value-of select="concat(name, ' ', ver)"/>
    Copyright <xsl:value-of select="copyright"/>, Laureate Learning Systems¨, Inc.
    Minimum System Requirements:
    300 MHz or faster PowerPC, Intel or better CPU
    Mac OS 8.1 or later, including any Mac OS X
    64 MB available RAM
    60 MB available disk space
    </body>
    </html>
    </xsl:template>
    </xsl:stylesheet>
    Yes. I do enjoy XSL quite a bit

  • Do shell script with SED

    I've used this a lot and have never observed this behavior; if it's normal I must really not have been paying attention.
    If I have a file (/Q.txt) which contains
    cnow
    cis the time
    cto call
    and do this: do shell script "sed 's/c//' < /Q.txt"
    the result is
    now
    is the time
    to call
    which is what I would expect.
    HOWEVER, if use this approach:
    set T to "cnow
    cis the time
    cto call"
    do shell script "echo " & quoted form of T & "| sed 's/c//'"
    the result is
    now
    cis the time
    cto call
    (I can't use the global form, as that will remove other instances of "c")
    The only way I can think this will happen is if "echo" removes the returns from T; but looking at the output of echo by itself the result looks okay. And the paragraph count of that result is the same as for T.
    What dumb thing am I doing now?

    Your issue is with the newlines (or other invisible characters) that are getting used. When I copied your example script, it worked as expected (the first match is replaced on each line). I don't know why the Script Editor would use different newline characters, but you can see from the following example how SED works with various ones:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #FFDDFF;
    overflow: auto;"
    title="this text can be pasted into the Script Editor">
    -- use a FF as the newline
    set T to "cnowc" & (ASCII character 10) & "cis the timec" & (ASCII character 10) & "cto callc"
    do shell script "echo " & quoted form of T & "| sed 's/c//'"
    --> correct
    -- use a CR as the newline (same as 'return')
    set T to "cnowc" & (ASCII character 13) & "cis the timec" & (ASCII character 13) & "cto callc"
    do shell script "echo " & quoted form of T & "| sed 's/c//'"
    --> same as your result
    -- the 'backslash-n' is a newline character that gets converted at compile time
    set T to "cnowc\ncis the timec\ncto callc"
    do shell script "echo " & quoted form of T & "| sed 's/c//'"
    --> correct
    -- replace all
    set T to "cnowc\ncis the timec\ncto callc"
    do shell script "echo " & quoted form of T & "| sed 's/c//g'"
    </pre>
    Since I can't see what you are using to generate the newlines (but they look the same), I am guessing that the wrong newline is getting placed in there. Copying from various sources may wind up with the different newline characters.
    Message was edited by: red_menace

  • Sending an email using shell script in Oracle Applications

    Hi,
    I have a pl/sql package which will call a shell script program.The shell script program is written in order to send the invoice hold details of AP as a mail.The parameters to this program are passed in the pl/sql package.
    The shell script program has
    5 parameters namely
    to - email
    from - email
    hold id - which is a number
    hold name - varchar2( free text)
    hold reason - varchar2( free text)
    the shell script looks as below.
    FROM_EMAIL=`echo $1|cut -f9 -d " "|sed 's/\"//g'`
    echo "From email id is $FROM_EMAIL" -- From email
    TO_EMAIL=`echo $1|cut -f10 -d " "|sed 's/\"//g'`
    echo "To Email id is $TO_EMAIL" -- to email
    PARAM0=`echo $1 | awk '{print $11}'|sed -e "s/\"//g"`
    echo "Param0: $PARAM0" -- hold id
    PARAM1=`echo "$1" | cut -d" " -f12-| sed -e "s/\" \"/\"^\"/g" | awk -F'^' '{print $1}'|sed -e "s/\"//g"`
    echo "Param1: $PARAM1" -- hold name
    PARAM2=`echo "$1" | cut -d" " -f13-| sed -e "s/\" \"/\"^\"/g" | awk -F'^' '{print $1}'|sed -e "s/\"//g"`
    echo "Param2: $PARAM2" -- hold reason
    the values that am passinf to this program are if suppose
    from email ---- [email protected]
    to email [email protected]
    12345 ------ hold id
    test hold name ------ hold name
    test hold reason ------- hold reason

    Is there a question here?
    In any case you could easily have done this inside the database using UTL_SMTP.

  • How to call a shell script from a java code

    Hello can any one suggest me how to call a shell script from a java program that takes three parameters.
    i have a shell script (msp_restore_gui) when i run this script in the command line in a RHEL5 ,SUSE10 and Debian machine it works fine .I even tested to call it from a java program and it also worked fine but when i used the same in a J2ee application where the user when clicks the restore button in a webserver this inturn sends the request to a java file named BackupManager.java where i call the shell script.But here it fails.Waiting for your suggestions.If you want i can put the code also here

    yes the script is in /usr/local/mss/tools/backup and the script (msp_restore_gui) is as follows
    #!/bin/sh
    TIMESTAMP=`date +%d_%b_%y-%H-%M`
    touch /var/backups/mss/mss_restore_"$TIMESTAMP".log
    LOGFILE="/var/backups/mss/mss_restore_"$TIMESTAMP".log"
    ### Explode tgz file
    cd /
    # Checks to be done:
    # root login
    # assume he passes the parameter as msp_backup_<timestamp>
    # check for the existence of the .tz and fileList.txt
    # Checking for the root login and if not logged on as root
    # permission will be denied to execute this script
    logmsg(){
    echo "`date`: $*" >> $LOGFILE 2>&1
    echo "$*"
    #usage of this script
    while [ $#  -ne 0 ]
    do
    case $1 in
    -n)
    shift
    ARCHIVE_NAME=`find / \( -name "$1.tz" -o -name "$1.tgz" \) 2>/dev/null`
    FILE_NAME=`find / -name $1_filesList.txt 2>/dev/null`
    if [ x$ARCHIVE_NAME = x -a y$FILE_NAME = y ]
    then
    logmsg "ERROR: Files not found, Restore cannot proceed"
    usage
    else
    tar tvzf $ARCHIVE_NAME > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
    echo "ERROR: The tar file $ARCHIVE_NAME is not proper. Restore cannot proceed"
    exit 1
    else
              echo "Backedup files are present, proceeding with restore......" >> $LOGFILE 2>&1
    fi
    fi
    usage
    SKIP_CLEANUP=1
    STATUS=1
    exit
    esac
    shift
    done
    rm -rf ./newfile
    curr_ver_file="/usr/local/mss/etc/version"
    /usr/local/mss/tools/backup/check_version $curr_ver_file $FILE_NAME
    ret_code=$?
    echo "Exit value of check_version is $ret_code"
    if [ "$ret_code" != 0 ]
    then
    logmsg "MSP Version not matching. Exiting from restore now...."
    errormsg=`cat /usr/local/mss/temp/ver_err_mesg`
    logmsg $errormsg
    rm -f /usr/local/mss/temp/ver_err_mesg
    exit 1
    else
    echo "Version check is successful"
    fi
    #### ShutDown MSS########
    /etc/init.d/mss stop
    sleep 2
    ### Shutdown semm
    /etc/init.d/semm stop
    sleep 2
    rm -rf `grep -v "MSP Version:" $FILE_NAME`
    logmsg "MSP restore in progress......"
    tar mxvfz $ARCHIVE_NAME >> $LOGFILE
    sleep 5
    ### Call mysql restore script
    /usr/local/mss/bin/mysql_alldb_restore.sh >> $LOGFILE 2>&1
    if [ $? -ne 0 ]; then
    logmsg "Database restore Failed. Cannot proceed further"
    exit 1 ;
    else
    logmsg "Database restore Succeeded."
    fi
    ### Remove DB Dump Files
    rm -f /var/lib/mysql-dumps/*
    ### Trigger cleanup of airprism database tables
    #touch /usr/local/mss/airprism/server/config/reinitdb
    ### Trigger re-import of software packages
    touch /usr/local/mss/swdepot/reimport
    ### Remove log files under the "apps" directory
    find /usr/local/mss/apps -name '*.log*' | xargs rm -f
    find /usr/local/mss/logs -follow -name '*[._]log*' | xargs rm -f
    if [ $? -ne 0 ]; then
    logmsg "MSP restore Failed. Cannot proceed further"
    exit 1 ;
    else
    logmsg "MSP restore Succeeded."
    fi
    # reinstall_patch is touched so that patches are re-installed after restoring of MSP.
    touch /usr/local/mss/patch/bin/reinstall_patch
    ##### Start MSS
    logmsg "restarting MSP server "
    /etc/init.d/mss start
    sleep 5
    ### Start semm
    /etc/init.d/semm start
    sleep 5
    logmsg "MSP server is now restarted"
    my jsp page backup.jsp is as follows
    <%@taglib uri="portlet.tld" prefix="uif" %>
    <%@taglib uri="msp-console.tld" prefix="msp" %>
    <uif:defineObjects/>
    <%@page import="javax.portlet.*" %>
    <%@ page import="java.util.Date" %>
    <%@ page import="java.util.Vector" %>
    <%@ page import="java.text.DateFormat" %>
    <%@ page import="com.symbol.mss.console.admin.backup.BackupManager" %>
    <%@ page import="com.symbol.mss.console.admin.system.SystemInfoPortlet" %>
    <%
         String STYLE_NAME = request.getParameter("style");
         if (STYLE_NAME == null) STYLE_NAME = STYLE_DEFAULT;
         final String ua = request.getHeader("User-Agent");
         BackupManager helper = null;
         PortletSession portletSession = renderRequest.getPortletSession();
         helper = (BackupManager)portletSession.getAttribute("helper");
         if (helper == null) {
              //System.err.println("Created new BackupManager");
              helper = new BackupManager();
              portletSession.setAttribute("helper", helper);
         final BackupManager backupManager = helper;
         String action = "";
         final String backupName = renderRequest.getParameter("backupName");
         String completePath = backupManager.getBackupDir() + backupName + backupManager.getBackupFileExt();
         if (backupName != null) {
              action = "backup";
         if(backupManager.backup(backupName)) {
              SystemInfoPortlet.beginRestartMSP();
              } else {
                   action = "backuperror";          
         final String cmd = renderRequest.getParameter("submitButton");
    final String selectedBackup = renderRequest.getParameter("selectedBackup");
    int tarFileStatus =0;
    String backupTarFile ="";
    String backupFileList ="";
         if ("Restore".equals(cmd)) {
    if (selectedBackup != null) {
         tarFileStatus = backupManager.verifyTarFile(selectedBackup);
         //backupTarFile = backupManager.getRestoreFile(Integer.parseInt(selectedBackup));
         //backupFileList = backupTarFile.substring(0, backupTarFile.lastIndexOf(backupManager.getBackupFileExt()))+"_filesList.txt";
                   if (tarFileStatus == 0){
         action = "restore";
         backupManager.restore(selectedBackup);
                        SystemInfoPortlet.beginRestartMSP();
              } else {
                   action = "error";
    } else if ("Remove".equals(cmd)) {
    backupManager.remove(Integer.parseInt(selectedBackup));
         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
         PortletURL restoreURL = renderResponse.createActionURL();
    %>
    <%@ include file="/jsp/core/constants.jspf" %>
    <% if (action.length() > 0) {
         if ("backup".equals(action))
    %>
         <p>The MSP Appliance has been shut down in order to create the <%=backupName %> backup file,
              and will automatically restart as soon as the file has been created.
              To continue your work, please log out of the MSP Console, wait for the appliance
              to restart, and then log back in. The amount of time you'll have to wait for the
              MSP Appliance to come back online depends on the amount of information you have
              stored in the MSP Database.</p>
         <p>The full pathname for the backup file is: <%=completePath %></p>     
    <%     }
         else if ("restore".equals(action))
    %>
         <p>The MSP Appliance has been shut down in order to restore from the <%=backupTarFile%> backup file,
              and will automatically restart as soon as the restore is complete.
              To continue your work, please log out of the MSP Console, wait for the appliance
              to restart, and then log back in. The amount of time you'll have to wait for the
              MSP Appliance to come back online depends on the amount of information you have
              stored in the MSP Database.</p>     
    <%     } else if ("backuperror".equals(action)) { %>
              <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> Errors occurred while taking back up of MSP. Please see the backup service log file for more details.
              </P>
    <%     } else if ("error".equals(action)) {
              if (tarFileStatus == 4) { %>
                   <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file <%=backupTarFile%> contains errors. This backup can't be restored. Please restore a valid back up.
                   </P>
              <%} else if (tarFileStatus == 3) { %>
                   <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file list <%=backupFileList %> is missing. This file is required to restoring backup. Please get the backup file list and proceed with restoring backup.</p>
              <%} else if (tarFileStatus == 2) { %>
                   <p> <img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file <%=backupTarFile%> contains errors and the backup file list <%=backupFileList%> is missing. This backup can't be restored. </p>
              <%} %>
    <%     }
    } else { %>
    <p><strong>Note</strong>: Both backup and restore will shut down MSP temporarily. MSP will be unable to collect data from devices, send notifications, or provide MSP Console access during this time. When the backup or restore operation is complete, MSP will come back online automatically.</p>
    <h3>Backup</h3>
    <form action="<%= restoreURL.toString() %>" method="post">
    <p>Please provide a name for your backup. MSP will provide the date automatically in the list of backups.</p>
    <p><label for="<uif:namespace />backupName">Name</label> <input type="text" name="<uif:namespace />backupName" id="<uif:namespace />backupName" size="20" maxlength="256" /> <input type="submit" name="<uif:namespace />submitButton" value="Back up now" onclick="return <uif:namespace/>validateName()"/></p>
    </form>
    <h3>Restore</h3>
    <p>This will restore all databases (device assets, collected device data, software packages, policies, etc.) to their state as of the time the backup was made. Changes since then <em>except for backups</em> will be destroyed.</p>
    <%
    Vector restoreList = helper.getRestoreEntries();
    Vector restoreDates = helper.getRestoreDates();
    Vector restoreVersions = helper.getRestoreVersions();
    Vector filesStatus = helper.getBackupFilesStatus();
    %>
    <% if (restoreList.size() == 0) { %>
    <p>There are no backups currently available.</p>
    <% } else { %>
    <form action="<%= restoreURL.toString() %>" method="post">
    <table class="input-radios" id="<uif:namespace />existingBackups">
    <thead>
    <tr>
    <th></th>
    <th>Name</th>
    <th>Date</th>
    <th>MSP Version</th>
    <th>Remarks </th>
    </tr>
    </thead>
    <tfoot>
    <tr>
    <td colspan="4" class="actionsOnSelected">
    <input type="submit" name="<uif:namespace />submitButton" value="Restore" onclick="return confirm('This action requires MSP and all related services to be shut down. Console will be unavailable if the request is submitted. The server will restart automatically once restore has been completed.');" />
    <input type="submit" name="<uif:namespace />submitButton" value="Remove" onclick="return confirm('This action will remove the backup archive. You will no longer be able to restore this backup. Continue?');" />
    </td>
    </tr>
    </tfoot>
    <tbody><%-- First one (most recent) is checked by default. Every other row has class="portlet-section-alternate". Note that each ID must be unique and must match the value of the "for" attribute on the corresponding "label" element. --%>
    <%
    for (int i = 0; i < restoreList.size(); i++) {
    %>
    <tr <%= (i % 2 == 1) ? " class=\"portlet-section-alternate\"" : "" %>>
    <td><input type="radio" name="<uif:namespace />selectedBackup" value="<%= i %>" id="<uif:namespace />selectedBackup-<%= i %>" <%= (i == 0) ? "checked=\"checked\"" : "" %> /></td>
    <td><label for="<uif:namespace />selectedBackup-<%= i %>"><%= restoreList.elementAt(i) %></label></td>
    <td><%= dateFormat.format((Date)restoreDates.elementAt(i)) %></td>
    <td><%= restoreVersions.elementAt(i) %></td>
    <td><%= filesStatus.elementAt(i) %></td>
    </tr>
    <%
    %>
    </tbody>
    </table>
    </form>
    <% } %>
    <% } %>
    <script type="text/javascript">
    <!--//--><![CDATA[//><!--
    function <uif:namespace/>validateName() {
    var name =document.getElementById("<uif:namespace />backupName");
    var msg= "<msp:i18n key="BackupMsg"/>";
    var str=name.value;
    var re = /^[A-Za-z0-9_]+$/;
    if (!str.match(re)) {
         alert(msg);
         name.focus();
         return false;
         } else {
    return confirm('This action requires MSP and all related services to be shutdown. Console will be unavailable if the request is submitted. The server will restart automatically once backup has been completed.');
    //--><!]]>
    </script>
    and my BackupManager.java is as follows where the code in bold and italic is called the restore()
    //============================================================================
    // Symbol Technologies P R O P R I E T A R Y S O U R C E C O D E
    // C O N F I D E N T I A L
    // Copyright (c) 2003 Symbol Technologies. All Rights Reserved.
    // All information contained herein is the property of Symbol Technologies,
    // or its Licensors, and are protected copyrights and trade secrets, and may
    // be covered by U.S. patents. Any reproduction or dissemination of any
    // portion of this document, of the software, or other works derived from it
    // is strictly forbidden unless prior written permission is obtained from
    // Symbol Technologies.
    //============================================================================
    package com.symbol.mss.sdf.services.backup;
    import java.io.*;
    import java.sql.Time;
    import java.text.DateFormat;
    import java.util.logging.FileHandler;
    import java.util.logging.Formatter;
    import java.util.logging.LogRecord;
    import java.lang.Process;
    import java.util.*;
    import org.apache.avalon.framework.configuration.Configurable;
    import org.apache.avalon.framework.configuration.Configuration;
    import org.apache.avalon.framework.configuration.ConfigurationException;
    import org.apache.avalon.framework.logger.LogEnabled;
    import org.apache.avalon.framework.logger.Logger;
    import com.symbol.mss.sdf.admin.AdministratorService;
    import com.symbol.mss.sdf.backup.*;
    import com.symbol.mss.sdf.data.*;
    * @author nramaiah
    * Service to perform scheduled backups of the system state.
    public class BackupManager implements BackupService, DataHandler,
    LogEnabled, Configurable {
    // MSS Home Path
    private static String mssHome = System.getProperty("phoenix.home", File.separator + "usr" +
    File.separator + "local" +
    File.separator + "mss" +
    File.separator);
    // Backup related definitions
    private static final String BACKUP_LIST_FILE_NAME = "conf" + File.separator + "files_to_backup.txt";
    private static final String BACKED_UP_LIST_FILE_NAME_SUFFIX = "_filesList.txt";
    private static final String BACKUP_LOCATION = File.separator + "var" + File.separator + "lib" +
    File.separator + "mss-backups" + File.separator;
    private static final String BACKUP_PARTITION = File.separator + "var" + File.separator + "lib";
    private static final String VERIFY_BACKUP = File.separator + "usr" + File.separator + "local" +
                                                           File.separator + "mss" + File.separator+"tools"+
                                                           File.separator+"backup"+File.separator+"verifyBackup.sh";
    // DB backup/restore related definitions
    private static final String DB_DUMP_LOCATION = File.separator + "var" + File.separator +
    "lib" + File.separator +
    "mysql-dumps" + File.separator;
    private static final String DB_BACKUP_SCRIPT = "bin" + File.separator + "mysql_alldb_backup.sh";
    private static final String DB_RESTORE_SCRIPT = "bin" + File.separator + "mysql_alldb_restore.sh";
    // Private variables
    private AdministratorService m_admin = null;
    private Logger m_logger = null;
    private String backupLocation = null;
    private String backupListFileName = null;
    private String backupPartition = null;
    private int backupPartitionLimit = 90;
    private String dbDumpLocation = null;
    private String dbBackupScript = null;
    private String dbRestoreScript = null;
    private List servicesBackupList = null;
    private String tarFileExtension =".tgz";
    private String errFileExtension =".err";
    private int exitValue=0;
    * Default Constructor
    public BackupManager() {
    servicesBackupList = new ArrayList();
    * Set the administrator service implementation. Link established by Broker service.
    * @param admin reference to an implementation of AdministratorService
    public void setAdministrator(AdministratorService admin) {
    m_admin = admin;
    * Set the job publisher service implementation. Link established by Broker service.
    * @param jobPublisher reference to an implementation of JobPublisherService
    public void setJobPublisher(DataChannel jobPublisher) {
    jobPublisher.subscribe(this);
    * Gets the backup manager object.
    * @return backup manager object
    public BackupService getBackupService() {
    return this;
    * Service lifecycle method.
    * @param logger logger object to be used by the service
    public void enableLogging(Logger logger) {
    m_logger = logger;
    * Service lifecycle method.
    * @param configuration service configuration object
    public void configure(Configuration configuration) throws ConfigurationException {
    // Verify MSS Home path
    if (!mssHome.endsWith(File.separator))
    mssHome += File.separator;
    // Get the location where the backup file needs to be placed
    backupLocation = configuration.getChild("BackupLocation").getValue(BACKUP_LOCATION);
    // Verify backup directory path
    if (!backupLocation.startsWith(File.separator))
    backupLocation = mssHome + backupLocation;
    if (!backupLocation.endsWith(File.separator))
    backupLocation += File.separator;
    // Get the file listing the files/directories to be backed up
    backupListFileName = configuration.getChild("FilesList").getValue(BACKUP_LIST_FILE_NAME);
    // Verify backup list file name path
    if (!backupListFileName.startsWith(File.separator))
    backupListFileName = mssHome + backupListFileName;
    // Get the partition where the backups are kept
    backupPartition = configuration.getChild("BackupPartition").getValue(BACKUP_PARTITION);
    // Verify backup partition path
    if (!backupPartition.startsWith(File.separator))
    backupPartition = File.separator + backupPartition;
    if (backupPartition.endsWith(File.separator))
    backupPartition = backupPartition.substring(0, (backupPartition.length()-1));
    // Get the limit on the amount of free space on the backup partition
    backupPartitionLimit = configuration.getChild("BackupPartitionLimit").getValueAsInteger(backupPartitionLimit);
    // Get the location where the DB dump files will be placed
    dbDumpLocation = configuration.getChild("DBDumpLocation").getValue(DB_DUMP_LOCATION);
    // Verify DB dump directory path
    if (!dbDumpLocation.startsWith(File.separator))
    dbDumpLocation = mssHome + dbDumpLocation;
    if (!dbDumpLocation.endsWith(File.separator))
    dbDumpLocation += File.separator;
    // Get the name of DB dump backup script
    dbBackupScript = configuration.getChild("DBBackupScript").getValue(DB_BACKUP_SCRIPT);
    // Verify backup script path
    if (!dbBackupScript.startsWith(File.separator))
    dbBackupScript = mssHome + dbBackupScript;
    // Get the name of DB dump restore script
    dbRestoreScript = configuration.getChild("DBRestoreScript").getValue(DB_RESTORE_SCRIPT);
    // Verify restore script path
    if (!dbRestoreScript.startsWith(File.separator))
    dbRestoreScript = mssHome + dbRestoreScript;
    * Individual services can supply a list of files/directories to be backed up.
    * These are files apart from the files specified in conf/files_to_backup.txt and
    * will be backed up as well.
    * @param files list of files/directories
    public void filesToBackup(List files) {
    synchronized(this) {
    if (files != null) {
    if (files.size() > 0) {
    // Add the list contents to the current backup list
    for (int i=0; i<files.size(); i++) {
    String tStr = (String)files.get(i);
    // Check for absolute or relative path
    if (tStr.startsWith(File.separator))
    servicesBackupList.add(tStr);
    else
    servicesBackupList.add(mssHome + tStr);
    else
    m_logger.info("Empty list of filenames. Nothing added.");
    else
    m_logger.info("Null list of filenames. Nothing added.");
    * Individual services can supply a list of files/directories to be backed up.
    * Specified files will be added to the file defining the list of files to be backed up.
    * @param files list of files/directories
    private void persistFilesToBackup(List files) {
    synchronized(this) {
    if (files != null) {
    if (files.size() > 0) {
    // Add the list of files provided to the end of file
    try {
    File file = new File(backupListFileName);
    if ((file == null) || (!file.exists()))
    file.createNewFile();
    // Seek to the end of the file
    RandomAccessFile rFile = new RandomAccessFile(file, "rw");
    if (rFile != null) {
    rFile.seek(rFile.length());
    // Write the list contents to the file
    for (int i=0; i<files.size(); i++) {
    String tStr = (String)files.get(i);
    // Check for absolute or relative path
    if (tStr.startsWith(File.separator))
    rFile.writeBytes(tStr + "\n");
    else
    rFile.writeBytes(mssHome + tStr + "\n");
    else
    m_logger.error("Error opening file " + backupListFileName);
    rFile.close();
    catch (Exception ex) {
    ex.printStackTrace();
    m_logger.error("Error adding entries to file " + backupListFileName, ex);
    else
    m_logger.info("Empty list of filenames. Nothing added.");
    else
    m_logger.info("Null list of filenames. Nothing added.");
    * Command to be run during the backup process. Individual services can
    * provide shell commands that will be executed before backing up the files.
    * @param command shell command to be executed
    private void runCommand(String command) {
    * Creates a shell script at the specified location that will backup the
    * files listed in the List passed in.
    * @param scriptFileName location where the script needs to be created
    * @param backupFileName name for the tar file being created
    * @param backupList list of files to be backed up
    private void createBackupScript(String scriptFileName, String backupFileName, ArrayList backupList) throws Exception {
    // Create a new StringBuffer to build the contents to be written to the script file
    StringBuffer buffer = new StringBuffer();
    // Add the initial comment in the start script
    buffer.append("#!/bin/sh\n" + "set -x\n\n");
    // Check if the partition has enough space
    buffer.append("### Check if the partition has enough space\n" +
    // "diskUsed=`df -k | grep \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1`\n" +
                   " diskUsed=`df -k \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1 | grep -v Use`\n" +     
    "echo \"Partition " + backupPartition + " is $diskUsed% used.\"\n" +
    "if [ \"$diskUsed\" -lt \"" + backupPartitionLimit + "\" ]\nthen\n" +
    " echo \"Starting backup...\"\n\n");
    // Shutdown semmd
    buffer.append(" ### Shutdown semm\n" + " /etc/init.d/semm stop\n" +
    " sleep 2\n\n");
    // MSP Limited release and earlier builds stop mysql DB and backup the
    // /var/lib/mysql directory as it is. Starting MSP 1.0 GA release, mysql
    // dump script will be integrated which will create sql scripts to
    // restore the database.
    // Check if mysql dump creation script exists
    File mysqlDumpScript = new File(dbBackupScript);
    if (mysqlDumpScript.exists()) {
    // MSP 1.0 GA and later releases
    // Run the script that will generate sql scripts that would re-create the DB as it is
    buffer.append(" ### Call mysql dump script\n" +
    " " + dbBackupScript + "\n\n");
    else {
    // MSP Limited release
    // Add command to shutdown mysql
    buffer.append(" ### Shutdown mysql\n" + " /etc/init.d/mysql stop\n\n");
    // Change to root directory and create the tgz file
    buffer.append(" ### Create tgz file\n" + " cd /\n");
    // Build up the tar file name from the current date and time
    String fileName = null;
    if ((backupFileName != null) && (backupFileName.length() > 0))
    fileName = backupFileName;
    else {
    // File name not provided by user, build one using the timestamp
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    fileName = "MSS-"
    + DateFormat.getDateInstance().format(date).replaceAll(" ", "").replaceAll(",", "")+ "-"
    + (new Time(cal.getTimeInMillis())).toString().replaceAll(":", "").substring(0,4);
    String tarFileName = fileName + ".tgz";
    // Get the current MSP Version
    String mspVersion = getMSPVersion();
    // Gather all the files to be backed up. Add them to the tar command and
    // also dump them into the file maintaining the list of files being backed up
    String listStr = "";
    for (int i=0; i<backupList.size(); i++)
    listStr += (String)backupList.get(i) + "\n";
    // Dump the current MSP version and the list of files being backed up into a manifest file
    String listFileName = fileName + BACKED_UP_LIST_FILE_NAME_SUFFIX;
    RandomAccessFile file = new RandomAccessFile(backupLocation + listFileName, "rw");
    m_logger.info("List of files/directories being backed up:\n" + listStr);
    file.writeBytes("### MSP Version: " + mspVersion + " ###\n");
    file.writeBytes(listStr);
    file.close();
    // Add the tar command to the script
    buffer.append(" echo \"Creating " + backupLocation + tarFileName + "...\"\n" +
    " tar cvhfz " + backupLocation + tarFileName + " `grep -v \"MSP Version:\" " +
    backupLocation + listFileName + "`\n\n");
    // Check if free space on the backup partition has reduced below the limit
    // If enough space left, backup is retained, "mss" is made the owner of the files,
    // "backup" is made the group the files belong to,
    // permissions changed to be "0660" and
    // backup action declared a success
    // Else, backup files are deleted and declared a failure
    buffer.append(" ### Check if the partition has enough space left\n" +
    //" diskLeft=`df -k | grep \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1`\n" +
    " diskLeft=`df -k \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1 | grep -v Use`\n" +
    " echo \"Partition " + backupPartition + " is $diskLeft% used.\"\n" +
    " if [ \"$diskLeft\" -gt \"" + backupPartitionLimit + "\" ]\n" +
    " then\n" +
    " ### Failure\n" +
    " echo \"Partition " + backupPartition + " does not have enough space.\"\n" +
    " echo \"Backup " + backupLocation + tarFileName + " will be removed.\"\n" +
    " rm -f " + backupLocation + fileName + "*\n" +
    " echo \"Backup Failed.\"\n" +
    " else\n" +
                        " tar tvzf " + backupLocation + tarFileName + " > /dev/null 2>&1\n" +
    " if [ ! -s " + backupLocation + tarFileName + " -o $? -ne 0 ] \n" +
                        " then\n" +
                        " echo \"MSP Backup operation is not successful. The tar file " + backupLocation + tarFileName + " contains errors.\"\n" +
                        " echo \"Please take the backup again\"\n" +
                        "     touch "+backupLocation+fileName+".err\n" +
    " else \n" +
    " ### Success\n" +
    " ### Change the owner, group and permissions for the backup files\n" +
    " chown mss " + backupLocation + fileName + "*\n" +
    " chgrp backup " + backupLocation + fileName + "*\n" +
    " chmod 0660 " + backupLocation + fileName + "*\n" +
    " echo \"Backup Completed.\"\n" +
    " fi\n" +
    " fi\n\n");
    // MSP Limited release and earlier builds re-start mysql. Starting
    // MSP 1.0 GA release, mysql is not stopped and so re-start is not
    // needed. sql scripts created by the dump script get packed into
    // the tar file and so are deleted.
    // Check if mysql dump creation script exists
    if (mysqlDumpScript.exists()) {
    // MSP 1.0 GA and later releases
    // Remove DB dump files
    buffer.append(" ### Remove DB Dump Files\n" + " rm -f " + dbDumpLocation + "*\n\n");
    else {
    // MSP Limited release
    // Start mysql
    buffer.append(" ### Start mysql\n" + " /etc/init

  • Error with dbms_scheduler and shell script execution

    Hi,guys.
    I have an issue with a dbms_scheduler and a shell script execution. So, the shell script as it self works fine, when i'm executing ./test.sh all process is running, but when i'm executing the script from dbms_scheduler it just simply doesn't work. Actually it works, but some of executable information in sh doesn't work, seems it just jump over of the part of the script. Sendmail part is running, maybe there is problem with rman script as it self?
    DB version: 10g
    And my scripts:
    Shell scripts (permisons 755):
    #!/bin/ksh
    export PATH=/home/oracle/product/asm_home/bin:/home/oracle/product/db_home/bin:/usr/bin:/etc:/usr/sbin:/usr/ucb:/home/oracle/bin:/usr/bin/X11:/sbin:.
    export ORACLE_BASE=/home/oracle/product
    export ORACLE_SID=zabbix
    export ORACLE_HOME=/home/oracle/product/db_home
    ${ORACLE_HOME}/bin/rman<<EOF
    connect target /
    run {backup recovery area delete all input;}
    EOF
    {       echo "From:[email protected]"
            echo "To: [email protected]"
            echo "Subject: Recovery area"
            echo 'Content-Type: text/html'
            echo
            echo '<html><body><table border="1" cellspacing="1">'
            echo '<tr><td><b>Process</b></td><td><b>Statuss</b></td></tr>'
            echo "<tr><td>RMAN</td><td><b>Works</b></td></tr>"
            echo "</table></body></html>"
    } | sendmail -tIn the first part i'm exporting all of the important stuff for oracle, then I call RMAN with specific atributes. And then there is just simply sendmail functionality inside script to represent if script works (for now).
    And below pl/sql script:
    begin
      DBMS_SCHEDULER.CREATE_JOB
      job_name => 'FLASH_RECOVERY',
      job_type => 'EXECUTABLE',
      job_action => '/home/oracle/backup/test.sh',
      start_date => sysdate,
      job_class => 'DEFAULT_JOB_CLASS',
      enabled => TRUE,
      auto_drop => FALSE,
      comments => 'FLASH RECOVERY USAGE AREA backup and delete'
      END;
      /And this job execution:
           begin
               DBMS_SCHEDULER.run_job (job_name =>'FLASH_RECOVERY',use_current_session => TRUE);
           end;What can be wrong? For me, I think it's something with permisions.
    I hope you got my idea and could help me.
    Tom
    Edited by: safazaurs on 2013.18.2 22:16

    There is no error, i just receive all the time e-mail, seems it jumps over rman. I tried almost everything and still couldn't get result as i want. And, if i'm running script from command line - it works. Rman calls, and starts to recover archivelogs.

  • Please help me remove the last elements of shell script from my applescript

    I read somewhere that running a shell script in an applescript was inefficient and created extra overhead, fine, so I am trying to take all of my shell script out of my applescript (this should fix issues with forward slashes in names as well...)
    however I am stuck on these last two lines (I know they are probably trivial but I've been up waaaay too long now) so I was wondering if anyone would be awesome enough to show me how to convert the bash to applescript.
    --does a recursive copy and rename
    do shell script "cp -R " & (thePath as text) & " " & (theOtherPathWithFile as text)
    --does a copy and rename, then a simple move
    do shell script "cp " & (quoted form of (POSIX path of this_item as text)) & " " & (theNewPath as text) & "&& mv " & (theOtherPathWithFile as text) & " ~/Desktop"
    Any and all help will be appreciated.

    There isn't anything wrong with using shell scripts, especially since AppleScript is designed to do this very thing. There is some overhead when using do shell script, just as there is some overhead when using an application tell statement, so it just depends on what you are doing.
    The performance of any particular script would also be up to whatever is acceptable to you (or your customers), and sometimes a shell script is the most efficient way to do something. Many of the system utilities are just GUI front-ends to a shell script, so they can't be all bad.
    To do your file copy or move with the Finder, you will need to tell it to duplicate or move the item(s) (there is that pesky overhead again). Shell scripts use POSIX paths while the Finder uses colons as its path delimiter, so you will need to use the correct file path references - there is a decent article about that at Satimage. Once your file paths have been defined (or using something like choose file or choose folder)), your script would be something like:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    font-weight: normal;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #DAFFB6;
    overflow: auto;"
    title="this text can be pasted into the Script Editor">
    tell application "Finder"
    duplicate source to destination
    -- move source to destination
    end tell
    </pre>
    See the Finder and *System Events* scripting dictionaries for more information about the ways they deal with files.

  • How to pass variables to shell script?

    I have a shell script which uses the touch command to change the date of a file.  To run the command on the command line the syntax is:
    set-file-date.sh <file> <date>
    I'm trying to run it from an automator workflow, so I'm prompted for the date, then the workflow iterates over the finder items, i.e., files, and changes the date of each files.
    The problem is in the "Run Shell Script" action.  The $@ is substituted with the file names selected in finder, so this will echo the file names:
    for i in "$@"; do
         echo "$i"
    done
    What I want to do is something like this:
    for i in "$@"; do
         set-file-date.sh <DATE VARIABLE> "$i"
    done
    But I can't prompt for the date value, and pass it to the script.  I've tried using the "Get Value of Variable" and the "Ask For Text" actions.  I can either get the file names from finder OR the text input in the "Ask for Text" action, but not both.
    Is what I'm trying to do possible with a shell script?
    -Thanks

    This is standard AppleScript text concatenation...
    set howManyWords to do shell script "wc -w /path/to/file | awk '{print $1}'"
    do shell script "/usr/local/bin/growlnotify -t 'Corpus' -m '" & howManyWords & " words were added to the corpus.'"
    in other words, just use the & to concatenate the parts of your text together.

Maybe you are looking for

  • Trying to add a php page to my existing template

    the title might not be what i have an issue with but its the best i could think of lol basically i have a site layout setup already now my site is at http://fgtestforum.info/daz (ive been told about ap divs already) ok in my menu under home you will

  • No Service for System SAPECC(Sender Port), Client800(R/3 system client 800)

    Hi friends, I am new to XI/PI I am working with IDOC to Flat file scenario I am facing the folllowing error. No Service for System SAPECC(Sender Port), Client800(R/3 system client 800) in integration Directory. can any one tell what was the reason fo

  • Can not login into messages app

    I have tried to login into the Messages app but continue to receive the following error messages. "Incorrect Apple ID or password."  Any suggestions?

  • System date issue

    Hi I have a java file which is reading data from datafile and insert into database. Now issue is upto 30 september(system date) program is working as expected. But after 30sept when system date chaned to 1st or second oct its not workin at all any id

  • ToolTip text disappearing

    I have a ( Swing ) GUI with buttons down the left side next to a graphics canvas. The ToolTip text which I have set for the buttons only appears over the panel and will not overlap onto the canvas. Is this a surmountable problem, or is it something t