Using launchctl command within a shell script

I have successfully installed two daemons, and I would like to be able to disable and enable them via shell scripts, called by the daemons themselves. Here is my first shell script:
#!/bin/sh
# Testing for presence of a CODEBOY file
if [ -e "/Volumes/CODEBOY/Change.txt" ]
then
osascript '/Users/praxisii/Library/Scripts/MacScript.scpt'
launchctl unload -w '/Users/praxisii/Library/LaunchDaemons/WaitDaemon.plist'
launchctl load -w '/Users/praxisii/Library/LaunchDaemons/RunDaemon.plist'
fi
The daemon works just fine, running the background, calling this script, which is waiting for me to plug in my flash drive (entitled CODEBOY). When the flash is plugged in, the applescript is called, and the first launchctl command is executed, which disables the WaitDaemon. As advertised, the .plist file is re-written with the Disabled key set to true. The next line (which is supposed to enable the RunDaemon) is never executed.
Similarly, if the launchctl line is placed before the osascript line, the applescript is never called. It is as if the shell ignores everything after a single launchctl command, which it will execute.
Any ideas or comments?

Gary:
Thank you for the link to the TN2083. Long, but very informative.
I appreciate all the other comments on this thread. I am an amateur AppleScript/UNIX scripter, and any opportunity to learn more is much appreciated.
I have completely re-worked my original launchd agent system for automatic processing of a file on a flash drive. Here is the .plist file that I now use:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>RunOSAscript</string>
<key>LowPriorityIO</key>
<true/>
<key>Program</key>
<string>/usr/bin/osascript</string>
<key>ProgramArguments</key>
<array>
<string>osascript</string>
<string>/Users/casdvm/Desktop/AutoFlash.scpt</string>
</array>
<key>RunAtLoad</key>
<false/>
<key>ServiceDescription</key>
<string>Runs Applescript directly</string>
<key>StandardOutPath</key>
<string>/Users/casdvm/Desktop/AutoFlashLog.txt</string>
<key>StartInterval</key>
<integer>25</integer>
</dict>
</plist>
The AutoFlash.scpt is an Applescript that simply uses the Finder to check for the presence of a specific file on the flash drive. If it is there, and a certain script property has a value of 2, then it runs the AppleScript that processes the desired file on the flash drive. Once that is done, the script property is set to 0 (to prevent the processing from happening over and over again.). Once the flash drive is removed, the script property is set back to 2 in anticipation of the next time the flash drive is plugged in.
It is much simpler than the two agents I was messing with beforehand. I did indeed discover that this .plist needs to be saved in the LaunchAgents folder of my user Library (thanks again for pointing that out, Gary).
The only problem that I have involves the continuous calling of the Applescript from the launchd agent. As you can see from my .plist file, that AppleScript is called every 25 seconds. I tried setting it up using the OnDemand key, but I kept receiving a re-spooling error of some sort (I don't recall exactly; my notes are sketchy on that phase of testing), so I just decided to have it go every 25 seconds. It really doesn't matter, since I can leave the flash drive plugged in all day anyway, and it only processes the desired file once.
Thanks again for all the commentary and discussion; I am grateful for the assistance.
Craig Smith

Similar Messages

  • Error Using dbms_scheduler to call a shell script

    Hi,
    I have been assigned a job of sending emails through unix utility(Mailx), based on certain activity in database.
    Email needs to be sent on insert/update of a column in one of the database tables.
    I am trying to use the block below to call the unix script responsible to send mails:
    begin
    dbms_scheduler.create_job
    job_name => 'TPP_SEND_EMAIL_JOB',
    job_type => 'EXECUTABLE',
    job_action => '/opt/ENV/code/BIL/users/usrbil01/Hemz/sndmailscrpt.ksh',
    repeat_interval => 'FREQ=MINUTELY; INTERVAL=30',
    enabled => true,
    comments => 'Send Email on ISU update'
    end;
    sndmailscrpt.ksh: Script to send email is embedded within the shell script
    I am getting the below error when i try to run the job using 'exec dbms_scheduler.run_job('TPP_SEND_EMAIL_JOB');'
    Error:
    ORA-27370: job slave failed to launch a job of type EXECUTABLE
    ORA-27300: OS system dependent operation:accessing extjob wrapper failed with status: 2
    ORA-27301: OS failure message: No such file or directory
    ORA-27302: failure occurred at: sjsec 3
    ORA-06512: at "SYS.DBMS_ISCHED", line 150
    ORA-06512: at "SYS.DBMS_SCHEDULER", line 441
    ORA-06512: at line 1
    I am not aware of any db related permissions that needs to be given, is this related to that or is there somethin i need to do for execution to be successfull
    Request you to let me know the exact solution and also the steps i need to take in order to ensure successfull execution of this script.
    Please also let me know if there is any other way wherein i can call a unix script from a database trigger on run time(i.e, whenever insert/update on a particular column in database)
    Regards,
    Hemanth

    Hi All,
    Thank you for your inputs.
    I am now pressed to explore the option of utl_mail as this dircetly sends mail from database. This is suggested as an option for my delivery now.
    I am able to install utl_mail and send a mail using the block below:
    begin
    utl_mail.send(
    sender => '[email protected]',
    recipients => '[email protected]',
    subject => 'Testing utl_mail',
    message => 'The receipt of this email is checking on working of UTL_MAIL '
    exception
    when others then
    dbms_output.put_line('error: '||sqlerrm);
    end;
    The block gets executed successfully, but i have not received a mail yet, is there a table or oracle log from where i can trace the delivery status for the mai, or if the mail is successfully sent too?
    I have heard from users in this forum for support of mime type "HTML", Should i pass the whole html body in the *'message'* input parameter here or can i pass a html template name with path present else where?
    Please do assist me in this regard.
    Regards,
    Hemanth

  • How to run a spool program in unix environment within a shell script

    Hi
    I have written a spool program , which i run from SQL * PLUS
    using
    @'path of the spool file having extension .sql'
    Now i want to include this spool program within the shell script , please help me , how to do it.
    Thanks in advance ..

    user8703472 wrote:
    Thank You Sir for the reply .
    #!/bin/ksh
    ORACLE_SID=<SID>; export ORACLE_SID
    ORACLE_HOME=<ORACLE_HOME>; export ORACLE_HOME
    $sqlplus / as sysdba <<-EOFSQL1 >> output.log 2>&1
    spool /tmp/a.log
    select * from v\$instance
    spool off;
    EOFSQL1
    Please explain me this statement $sqlplus / as sysdba
    and also what a.log contains .
    i have the user id and password for the DB.
    should i write something like this
    $sqlplus -Uusername -Ppassword -Sservername
    i know how to run a procedure from isql(sybase DB)
    Ahh.... but oracle is not just sybase under a different name.
    It would be a good investment in your career to go to tahiti.oracle.com. Drill down to your product and version. There you will find the complete doc library.
    You should spend a few minutes just getting familiar with what kind of documentation is available there by simply browsing the titles under the "Books" tab.
    Open the Reference Manual and spend a few minutes looking through the table of contents to get familiar with what kind of information is available there. Learning where to look things up in the documentation is time well spent on your career.
    For your immediate task, spend a few minutes looking through the SQLPlus User Guide and Reference.
    Then set yourself a plan to dig deeper.
    - Read a chapter a day from the Concepts Manual.
    - Look in your alert log and find all the non-default initialization parms listed at instance startup. Then read up on each one of them in the Reference Manual. Take a look at your listener.ora, tnsnames.ora, and sqlnet.ora files, then bounce what you see there in the network administrators manual.
    Give a man a fish and he eats for a day. Teach a man to fish and he eats for a lifetime.
    But this project , i need to run the spool program from with in a shell script .We see what you mean, but the term "spool program" has no meaning in Oracle and only serves to cloud the issue. I know you are used to using this term with other products, but "When in Rome ...."
    >
    Thank You in advance ..

  • Exit command in a Shell Script

    I am trying to input an 'exit' command in a shell script. I am running Solaris 8. I have checked all of my documentation on the OS and cannot find the command syntax. Can someone help me? Thanks.

    #!/usr/bin/env bash
    # This a simple bash script outlining the procedures to get macports on OS X
    # to auto update weekly via the ~/Library/LaunchAgents/net.ipatch.macportsUpdate.plist
    # The first step is to update the port files
    echo "Step 1: Update port tree"
    port selfupdate
    # The second step is to upgrade the outdated
    echo "Step 2: Upgrade outdated"
    port upgrade outdated
    # The third step is to remove inactive ports
    echo "Step 3: Remove inactive ports"
    port uninstall inactive
    # The fourth step is to clean the vile
    echo "Step 4: Clean the vile"
    port clean --all vile
    Now invoke your script using sudo, as in:
    sudo ./macportsUpdate.sh
    This way you authentiate once, and from that point forward everything is run a 'root'
    If you do not want to remember to prefix the script with sudo, then you could do the following:
    #!/usr/bin/env bash
    myPortUpdate()
    # This a simple bash script outlining the procedures to get macports on OS X
    # to auto update weekly via the ~/Library/LaunchAgents/net.ipatch.macportsUpdate.plist
    # The first step is to update the port files
    echo "Step 1: Update port tree"
    port selfupdate
    # The second step is to upgrade the outdated
    echo "Step 2: Upgrade outdated"
    port upgrade outdated
    # The third step is to remove inactive ports
    echo "Step 3: Remove inactive ports"
    port uninstall inactive
    # The fourth step is to clean the vile
    echo "Step 4: Clean the vile"
    port clean --all vile
    # Now do all of the above with a single sudo command
    sudo myPortUpdate
    Now you can invoke the script and it will just prompt once for your admin password
    macportsUpdate.sh
    Message was edited by: BobHarris

  • Run Unix command / Run Unix shell script from Forms9i

    Hi,
    I have a requirement to run Unix command and Unix shell scripts from Forms9i.
    I know HOST command cannot be used directly. I also know we can create some JAVA stored procedure to perform the task, but I don't want to create any JAVA stored procedure as there are some security concerns.
    Please point me towards any other way to achieve the same.
    I would really appreciate your help.
    Thanks,
    Kumar

    There is no reason why HOST can't be used. This is what it is for. As for using Java, it is not a stored procedure that you would be using, it would be imported Java (imported into the form).
    The best way to use the HOST command is to call a script (.sh) rather than calling a Unix command directly. This is because HOST will not pick up environment variables set at the system level. So the script would first need to set the necessary environment variables then call the desired commands.

  • Use java to run a shell script which called a crontab command at Unix

    I was trying to write an automate function using Java, which needs to call a shell script containing a crontab commend. The shell works fine without that crontab commend, but once I add it, the program won't execute that crontab commend.
    public void cron(){
    try
    Process proc = Runtime.getRuntime().exec("script1");
    BufferedReader br = new BufferedReader(new           InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = br.readLine()) != null)
         System.out.println(line);
    int returnValue = proc.waitFor();
    br.close();
    } catch (Exception e){} //
    script1:
    #!/bin/sh
    crontab cronfile
    Can someone help me out for this? Thank you.

    Try this....
    Process p = Runtime.getRuntime().exec("sh");
    java.io.BufferedWriter bw = new java.io.BufferedWriter(new java.io.OutputStreamWriter(p.getOutputStream()));
    bw.write("script1");
    bw.flush();
    bw.close();

  • Starting and stopping an SQL query from within a Shell script

    DB version:10gR2
    OS Version:AIX
    We have a C++ application called WpnCreate.cpp, which is causing some locking problems.
    So, we have decided to capture(using SPOOL) the locking info(session info, blocking program,..etc) using an SQL query.
    WpnCreate.cpp program is initiated by a shell script. So we need this SQL query(.sql) to start firing just before WpnCreate.cpp is called and when WpnCreate.cpp has finished executing, we need the SQL query execution to stop.
    But how do i stop the sql query execution? Should i capture the session id and serial# of this session and use kill -9 at the end of the shell script?
    Flow of the Shell script should be like this
    Step1. Start firing the SQL query which captures the locking info and SPOOL them to a file
    Step2. Execute WpnCreate.cpp program
    Step3. Stop the firing of SQL query once WpnCreate.cpp has finished executing ( i don't know how)How will i go about achieving this?

    How can you run your step 2 untill & unless your step 1 gets over. You can run in background but then it will not capture the correct information.
    I think you need to run your step 1 after step 2 , then only you will be able to capture the information.
    You can run your C++ program in background and can wait for some time using sleep command and then run the query to check the locking information.

  • NoClassDefFoundError when using Runtime to call a shell script

    I have a java program that uses the Runtime.exec method to call a shell script that then calls another java program (the shell script and 2nd java program are a 3rd party product I have to call).
    When I run my program as root, it works fine. When I run it as a regular user, I get the following error message:
    Exception in thread "main" java.lang.NoClassDefFoundError: 'argument'
    In the error message above, "argument" is just an argument I had to pass to the shell script, which then calls the 2nd java program. It is this second java program that is throwing this exception it seems. This is all in Linux (RH AdvSrvr 2.5). If I call the shell script on the command line as the regular user, not from the java program, it works fine; but I NEED to call it from the java program... it's a long story.
    I have check Environment variables, system properties under both users during the processes and I cannot find any major difference. I have checked file permissions and everything.
    Does anybody have a clue what is going on here? Please help me, thank you!

    Okay, we found the problem. Our in-house MASTER OF ALL found it. The argument that the jvm was trying to load as a class needed to be in quotes according to documentation, but the shell escapes out the quotes when run on the command line, whereas in my java process it was not, therefore the jvm thought it needed to load it as a class.
    Clear as mud?

  • [SORRY] exec command problem for shell scripting

    I know this is not an appropriate place to ask questions about shell programming, but I have tried many other places... and no helpful help yet. So, here I am.
    I am writing a simple shell script that would actually execute a java application. However, I want to give the users the option of running it in background. So,
    COMMAND="java blahblah"
    DAEMON="&"
    exec "$COMMAND $DAEMON"
    But, when I run it, it spits out an error message saying something like "Invalid agrument: &".
    Is there a way to exec'ing "java blahblah &" using variables as arguments to "exec" command???
    OR is it even NOT possible?
    This problem seems so trivial, but took a man out of me. :( Please help.
    thanks
    yosep

    execute a java application. However, I want to give
    the users the option of running it in background. It doesn't generally make sense to exec an ansynchronous process, and one can introduce varying errors in this method. Just simply drop the exec. The java process will async off and the shell script will exit leaving no shell process running. Simple as that.
    BTW, you generally exec a java process if you wish to replace the shell with the java process, but then the async request is given at the caller, she who actually calls the script (genarally from an interactive shell).

  • Reloading a File within a shell script

    Hi
      Is there a way to reload a file that has just been updated within  shell script. As i want to read the updated content of the file for the rest of the command inside my script

    Hello,
    I have answered this in your other question.
    Regards,
    Siddhesh

  • Translating working UNIX command to "do shell script"

    A few days ago LittleSaint and Gary Kerbaugh (UNIX discussions) suggested an approach for text positioning which appears to work flawlessly in Terminal. The UNIX version is:
    awk -v str_x="140 280" -v str_y=abcdef 'BEGIN{ printf "%-13s%s\n", str_x, str_y }'
    Now, I'm trying to use this in AS as a "do shell script". Clearly, some changes are needed (characters escaped, punctuation changes, etc.), but I've been unable to nail down exactly what those are (assuming it's even feasible).
    Ideas?

    How about this:
    do shell script "awk -v str_x=\"140 280\" -v str_y=abcdef 'BEGIN{ printf \"%-13s%s\\n\", str_x, str_y }'"

  • Return codes from sqlldr command from unix shell script

    I am trying to capture error code from sql loader from unix shell script and display proper messages.
    sqlldr parfile=sdb.par control=$cntlfile data=$infile bad=$badFile log=$logFile rows=10000
    rows=10000
    retcode=`echo $?`
    case "$retcode" in
    0) echo "SQL*Loader execution successful" ;;
    1) echo "SQL*Loader execution exited with EX_FAIL, see logfile" ;;
    2) echo "SQL*Loader execution exited with EX_WARN, see logfile" ;;
    3) echo "SQL*Loader execution encountered a fatal error" ;;
    *) echo "unknown return code";;
    esac
    Eventhough, there are errors while executing sqlldr, it is always returing recode zero. What could be the possible reason
    Please advice

    Is there a typo in your code ?
    sqlldr parfile=sdb.par control=$cntlfile data=$infile bad=$badFile log=$logFile rows=10000
    rows=10000
    retcode=`echo $?` In this code, you get the return code of the statement in bold which is not the sqlldr statement ...

  • How to use the result of simple shell script?

    The shell script below retrieves the length of an audio file:
    set aFile to choose file
    do shell script "afinfo " & quoted form of (POSIX path of aFile) & "|grep duration"
    I'm wondering, how can I copy the result to the clipboard or set the value of a variable to it?
    Total newbie question. I have no idea about shell scripts - I just found the script above online.
    Thank you so much!

    Here:
    set the clipboard to (do shell script "afinfo " & quoted form of (POSIX path of aFile) & "|grep duration")
    or:
    set A to do shell script "afinfo " & quoted form of (POSIX path of aFile) & "|grep duration"
    (53997)

  • Passing parameters to shell command within a MAXL script

    Hi all,
    we are trying to run the following from MAXL console
    MAXL> msh script.msh 100 c:\t.txt
    where script.msh has the line:
    shell 'echo $1 >> $2'
    we are looking to add a line with text "100" to the file C:\t.txt but it's actually creating a file called $2 with the text "$1" within it.
    How can we workaround it?
    Thanks

    If I understood well you command line, we would have .log and .err files but .err would be also redirected to .log apart from .err, right?^^^Exactly. That way you can look at either stream, or both. If you think about it, you could test for the existence of any .err file (or come up with your own unique extension for that directory) and flag that after the fact with an email, and attach the specific error and the overall stream. Mind you, given the size of your files, you might want to zip them down first.
    It's the best (or, depending on your outlook, the worst) of all worlds.
    Scripting is one of those things that isn't very sexy, and when it's done well it just fades into the background and doesn't get the credit it deserves. But when it blows up or is kludgy beyond compare it makes everyone's life miserable.
    Regards,
    Cameron Lackpour

  • Using OS Commands within PL/SQL

    How can I use Operating system commands from within PL/SQL procedures or functions? Kindly explain with an example.
    Thanx,
    SB

    Previously we have used external procedures to use Windows kernel32.dll to start an external program. However this does not work on Oracle9i.
    Instead I have modified an example in Java to acceive this. The following class can start an external program either synchronously or asynchronously and in synchronous mode it will return the programs output.
    import java.io.*;
    import java.util.*;
    public class util
    // Executes an operating system command. The command shall be fully qualified.
    // The Java connects with silent login. No environment set-up files are run
    // and no path is set. The mode can be "sync" or "async" for respectively
    // synchronous and asynchronous execution
    static public int OSCmd(String cmd, String mode, String[] output)
    throws IOException, InterruptedException
    System.out.println("OSCmd "+cmd+" ("+mode+")");
    output[0]="";
    // start command
    Process proc = Runtime.getRuntime().exec(cmd);
    if (mode.equals("sync"))
    // get command's stdout and stderr
    InputStream stdout = proc.getInputStream();
    InputStream stderr = proc.getErrorStream();
    String str;
    // Stdout
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
    while ((str = br.readLine()) != null)
    output[0]+=str+"\n";
    br.close();
    // Stderr
    br = new BufferedReader(new InputStreamReader(stderr));
    while ((str = br.readLine()) != null)
    output[0]+=str+"\n";
    br.close();
    // wait for command to terminate
    proc.waitFor();
    return proc.exitValue();
    return 0;
    You need the following permissions:
    call dbms_java.grant_permission('COMMON', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'execute');
    call dbms_java.grant_permission('COMMON', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    call dbms_java.grant_permission('COMMON', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    And then create the Java stored procedure:
    create or replace function os_cmd2(p_cmd varchar2, p_mode varchar2, p_output in out varchar2) return number
    as language java
    name 'util.OSCmd(java.lang.String, java.lang.String, java.lang.String[]) return int';

Maybe you are looking for

  • When i create a pdf in adobe standard get a unable to find adobe pdf resource file

    when i create a pdf in adobe standard get a unable to find adobe pdf resource file

  • ORA- Error messages in Oracle Alert File

    Hello Gurus, In a SAP - BW system installed on Oracle 8.1.7.4, there were some oracle errors entries as follows; Fri Nov  3 02:13:32 2006                                            Errors in file /oracle/<SID>/saptrace/background/p001_14866_<sid>.trc

  • Don't remember my password, now my phone won't sync!

    I enabled "encrypt iphone backup on itunes, but forgot the password. Now my phone will not sync. Is there any way that I can retrieve my password? Thanks!

  • Tabular form template

    Hi all, I'm looking for a special template on tabular forms. It should provide different form elements only for a row that is in edit mode or in input mode. The other rows should be display_only_html. has someone done this before? thanks franz

  • BTF Editor -disable buttons

    Hi , I want to disable some standard buttons (like bold button) which were displayed in BTF editor toolbar. Are there any options to do it.. i have search the class cl_btf , cl_btf_editor  for this..but couldn't make out. Thanks, Sandy.