Executing sequence of commands using exec

How do I execute sequence of commads using java.lang.Runtime.exec()?
As a part of an assignment, I need to use the exec command to
a. change drive and then
b. change directory and then
c. execute some command.
Thanks.

windows
"pushd <dir path> && <some command>"

Similar Messages

  • How to execute XML batch commands using SharePoint Web services or Client Object Model

    Hi,
    I have a requirement to execute some batch commands to update SharePoint View Style, how can i do it using SharePoint webservices or SharePoint Client Object model.
          I need to execute the following Batch command over a particular web.
    <Method ID="UpdateView">
      <SetVar Name="Cmd">UpdateView</SetVar>
      <SetList Scope="Request">{GUID of List}</SetList>
      <SetVar Name="View">{GUID of View}</SetVar>  
      <SetVar Name="ViewStyle">6</SetVar>
      <SetVar Name="RowLimit">100</SetVar>
      <SetVar Name="Paged">TRUE</SetVar>
    </Method>

    Hi
    I tried it already... But UpdateView Method in the Views.asmx and Lists.asmx, both are not supporting for updating the style of the view (like Boxed, Newsletter...).
    If you have any code sample which will do this job with any of the SharePoint web services, please share it..

  • How to execute a cvs command using System Call?

    hi all,
    how to execute a cvs login command using system call ?
    thanks,
    dam

    To anyone that reached this post and still dont have a hint, try this small sample - it logs on CVS using installed CVSNT and execute a fake update:
    package testeCVS;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    public class execCMD
        String password="yourPassword";
        String directory="C:\\CVS\\yourPathToProject";
        //send commands to CVS and shows the resulting screen
        public int sendCMD(String[] command) throws IOException, InterruptedException
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory(new File(directory));
            pb.redirectErrorStream(true); // merge stdout and stderr
            Process p = pb.start();
            InputStreamReader isr = new  InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String lineRead;
            StringBuilder buffer=new StringBuilder();
            System.out.println("Return of shell:");
            while ((lineRead = br.readLine()) != null)
                buffer.append(lineRead + "\n");
            System.out.println(buffer.toString());
            return p.waitFor();
        //send commands to CVS, send the password after the prompt and show the resulting screen
        public int sendDialogCMD(String[] command) throws IOException, InterruptedException
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.directory(new File(directory));
            pb.redirectErrorStream(true); // merge stdout and stderr
            Process p = pb.start();
            PrintWriter writer = new PrintWriter( new OutputStreamWriter( p.getOutputStream() ));
            writer.println( password );
            writer.flush();
            InputStreamReader isr = new  InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String lineRead;
            StringBuilder buffer=new StringBuilder();
            System.out.println("Return of shell:");
            while ((lineRead = br.readLine()) != null)
                buffer.append(lineRead + "\n");
            System.out.println(buffer.toString());
            return  p.waitFor();
        public static void main(String a[]) throws IOException, InterruptedException
            execCMD e=new execCMD();
            String[] command = new String[5];
            command[0] = "cvs";
            command[1] = "-q";
            command[2] = "-d";
            command[3] = ":pserver:yourUserID@localhost:2402/path/of/yourProject"; //in this case using CVS port 2402
            command[4] = "login";
            System.out.println("exit value=" + e.sendDialogCMD(command));
            command = new String[8];
            command[0] = "cvs";
            command[1] = "-q";
            command[2] = "-d";
            command[3] = ":pserver:yourUserID@localhost:2402/path/of/yourProject";
            command[4] = "-n";
            command[5] = "-q";
            command[6] = "update";
            command[7] = "-dA";
            System.out.println("exit value=" + e.sendCMD(command));
    }It is possible to send the password on the same command, but I had problems when the password had the character '@' because CVSNT took it as the separator between the username and server name. In that case the command is: ":pserver:yourUserID:yourPassword@localhost:2402/path/of/yourProject"

  • Problem while executing a command using exec()

    I'm trying to execute a command on Unix O/S with the help of java program. For this I have used Runtime class available in java.lang. It works fine for some of the basic unix commands like 'ls','cp' but when I tried to execute command "sqlldr userid=<user>/<pwd> control=/u01/dw/snb/log/sp_shd05721_ins_stg_sqlldr.ctl" , then it's not getting executed. Please advise.

    You may be having a problem with the command path, which I don't think Runtime.exec() uses. Try specifying the full path

  • Error while Executing Unix Shell Commands Using Runtime clas

    I am trying to run the following code in java on unix machine to execute cat command.
    Runtime runtime = Runtime.getRuntime();
              try {
                   System.out.println("before catexecute");
                   Process process = runtime.exec("cat /export/home/shankerr/local.profile > /export/home/shankerr/local1.txt");
                   try {
                        if (process.waitFor() != 0) {
                        System.err.println("exit value = " +
                                  process.exitValue());
                        catch (InterruptedException e) {
                        System.err.println(e);
    But i get the following error on the console
    exit value = 2
    cat: cannot open >
    cat: cannot open /export/home/shankerr/local1.txt
    The same command if i run on unix console directly it creates a new file and copies the content into the new file local1.txt
    kindly help me on the same

    The redirection operator > along with stuff like pipe | history !$ etc. is interpreted by the shell, not by the cat program.
    When you do cat X > Ycat only sees the X. The rest is interpreted by the shell to redirect the cat program's stdout.
    However, when you Runtime.exec(), you don't have the shell, so cat sees X > Y as its arguments, and interprets them all as file names. Since there's no file named > you get the error.
    The solution is to first man cat on your system and see if it happens to have a -o or somesuch operator that lets it (rather than the shell) send its output to a file. If not, then you need to invoke a shell, and pass it cat and all of cat's args as the command to execute.
    Read the man pages for you shell of choice, but for bash, I believe you'd give Runtime.exec() something like /bin/bash -c 'cat X > Y'

  • Executing external native processes using exec

    Hi,
    I am running an external process in the normal way (i.e using Runtime.exec to reutrn a process object, using process.waitfor() to wait for return code etc). However, what I need is for the external process to continue running after my java application has exitted. So far I have been unable to do this � it seems the external process is still somehow a child of my Java process.
    Does anyone have any idea how to do this, or even if it is possible?
    Thanks in advance!

    If you detach the child process (redirect stdin, out, err) from the starting one it should be no problem. waitfor() is of course not applicable.

  • How to execute multiple SSH commands using Ganymed

    I try to use Ganymed SSH to send and receive commands to/from the SSH server.
    However Ganymed example shows only sending one single SSH command to the SSH server.
    Does anybody know how to send and receive multiple commands to/from SSH server?

    I tried many times and it did not work. Please help.
    The output is this :
    Last login: Tue Oct  6 23:05:10 2009 from 192.168.1.4
    /bin/ls -aldf -k[root@linux ~]# /bin/ls -aldf -kExit status : nullI enclose the
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.KnownHosts;
    import ch.ethz.ssh2.Session;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    public class TestClient01 implements Runnable {
        static final String knownHostPath = "~/.ssh/known_hosts";
        static final String idDSAPath = "~/.ssh/id_dsa";
        static final String idRSAPath = "~/.ssh/id_rsa";
        private String host = "192.168.1.2";
        private String username = "root";
        private String password = "1234567";
        private KnownHosts database = new KnownHosts();
        private OutputStreamWriter writer = null;
        private Connection conn = null;
        private Session sess = null;
        public void writeCommand(String s) {
            try {
                writer.write(s);
                writer.flush();
            } catch(Exception ex) {}
        public void close() {
            if (writer==null) return;
            try {
                writer.close();
                sess.close();
                conn.close();
            } catch(Exception ex) {}
            if (writer!=null) writer = null;
        public void run() {
            try {
                conn = new Connection(host);
                conn.connect();
                boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                if (!isAuthenticated) throw new IOException("Authentication failed.");
                sess = conn.openSession();
                new Thread(new SyncPipe(sess.getStderr(), System.err)).start();
                new Thread(new SyncPipe(sess.getStdout(), System.out)).start();
                sess.requestPTY("bash");
                sess.startShell();
                writer = new OutputStreamWriter(sess.getStdin(), "utf-8");
                writeCommand("/bin/ls -al");
                writeCommand("df -k");
                sess.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF |
                        ChannelCondition.EXIT_STATUS, 10000);
                System.out.println("Exit status : " + sess.getExitStatus());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                System.exit(2);
        public static void main(String[] args) throws Exception { new TestClient01().run();}
        class SyncPipe implements Runnable {
            String CVS_VERSION = "$Revision: 1.1 $ $Id: SyncPipe.java,v 1.1 2008-09-30 03:47:56 sabre Exp $ ";
            private final byte[] buffer_;
            private final OutputStream ostrm_;
            private final InputStream istrm_;
            private boolean closeAfterCopy_ = false;
            public SyncPipe(InputStream istrm, OutputStream ostrm) { this(istrm, ostrm, 4096);}
            public SyncPipe(InputStream istrm, OutputStream ostrm, int bufferSize) {
                if (istrm == null) throw new IllegalArgumentException("'istrm' cannot be null");
                if (ostrm == null) throw new IllegalArgumentException("'ostrm' cannot be null");
                if (bufferSize < 1024) throw new IllegalArgumentException("a buffer size less than 1024 makes little sense");
                istrm_ = istrm;
                ostrm_ = ostrm;
                buffer_ = new byte[bufferSize];
            public void handleException(IOException e) { e.printStackTrace();}
            public SyncPipe setCloseAfterCopy(boolean closeAfterCopy) {
                closeAfterCopy_ = closeAfterCopy;
                return this;
            public void run() {
                try {
                    for (int bytesRead = 0; (bytesRead = istrm_.read(buffer_)) != -1;)
                        ostrm_.write(buffer_, 0, bytesRead);
                    ostrm_.flush();
                    if (closeAfterCopy_) ostrm_.close();
                } catch (IOException e) { handleException(e);}
    }

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

  • Trying to use grep from within java,using exec command!

    Hi all!
    I would like to run a grep function on some status file, and get a particular line from it, and then pipe this line to another file.
    Then perfom a grep on the new file to check how many of the lines above are present in that file, and then write this value to a new file.
    The final file with a numerical value in it, i will read from within java,as one reads normal files!
    I can run simple commands using exec, but am kinda stuck with regards to the above!
    Maybe i should just do all the above from a script file and then run the script file from exec. However, i dont want to do that, because it kinda makes the system dependent,..what if i move to a new machine, and forget to install the script, then my program wont work!
    Any advise?
    Thanks
    Regards

    With a little creativity, you can actually do all that from the command line with a single command. It'll look a little crazy, but it can be done.
    Whether the script exists on the local machine or not has zero to do with platform indpendence. You assumedly have to get the application onto the local machine, so including the script is not really an issue at all. However, you're talking about system independence, yet still wishing to run command line arguments? The two are mutually exclusive.

  • Re: Error while Execute External Operating System Command using T.code SM49

    Dear Experts,
    I Have uploaded one .exe file in the application server (eg: sum.exe) and created the OS command in SM69 transaction .
    And maintained the application server path in the 'operating system command' field in SM69 t.code.
    Our SAP system, oprating system is UNIX.
    After I have executed the external command using transaction SM49 , but I got the below error.
    Can not execute external program (permission denied) , External program terminated with exit code 1
    Immediately I run the SU53 transaction code to check the authorization, but Authorization was successful.
    Could any one please help on this error.
    Thanks in advance.

    >>Can not execute external program (permission denied) , External program terminated with exit code 1
    You need to give the permission as 755 to your file.
    >>I Have uploaded one .exe file in the application server (eg: sum.exe)
    You are on UNIX and do not expect to any result of .exe file as UNIX doesn't know about this.

  • To execute external command using   RFC_REMOTE_exec

    Hi
    i want to execute the ext command using RFC_REMOTE_EXEC .
    i have used like below in WINDOWS XP:
    data: v_cmnd(120) type C VALUE 'dir C:\SAP\rfcsdk\bin >RFEXEC -D ESM_R'.
    call function 'RFC_REMOTE_EXEC' destination D_DESTI
    exporting
    command = v_cmnd
    exceptions
    system_failure = 1 message D_ERMSG
    communication_failure = 2 message D_ERMSG.
    manually at command line the program getting registerd but
    not throuergh RFC_REMOTE_EXEC 
    in v_cmnd  what is the exact value we have to give
    Regards

    you create the command in SM69 with some name and Directly give the Same name when you are executing.
    Check this Function also.
    SXPG_COMMAND_EXECUTE

  • Executing Windows shortcuts through getRuntime.exec

    Hello,
    I am writing a desktop component in which you should be able to drag and drop local windows icons and they will become an icon on my desktop.
    I am able to get the shortcut .lnk location by accessing the list flavor from the native drag and drop... for example if i drop a native shortcut i get:
    C:\Documents and Settings\pankaj\Desktop\Shortcut to eclipse.lnk
    i can even access the file system icon by:
              ImageIcon iconImage = (ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(execFile);
              iconImage.setImage(iconImage.getImage().getScaledInstance(32,32,Image.SCALE_AREA_AVERAGING));
    but i tried to execute the .lnk command using getRuntime.exec(cmd); it didnt work obviously.. how can make this work?
    you can check out info on my project here:
    http://www-unix.globus.org/cog/wiki/moin.cgi/JavaCogDesktop
    thanks.
    pankaj

    Did you try "start"?
    new String [] { "cmd" , "/c", "start" , "path-to-my-shortcut" }

  • Failed using exec and wait_for_file functions in Unix for DS X3.1

    Hi,
    Unix version --> 11.23 running of HP-UXIA64
    DS version   --> Data Services X3.1
    I able to run exec and wait_for_file fuctions in my local Windows environment using cmd.exe to move files or copy files around folders.
    A) However, I failed to run Unix command using exec function to get any similar results, the test script that i wrote in DS is like this:
    (1) DS Scripts:
    ==========
    $G_Var1 = exec('/usr/bin/sh', 'pwd', 8);
    Print('**** Unix result: \[$G_Var1\] ****');
    log returns as such:
    ==================
    PRINTFN     5/12/2008 11:56:35 AM     **** Unix result:       1: pwd: invalid multibyte character ****
    (2) DS Scripts:
    ==========
    $G_Var1 = exec('', '/usr/bin/sh pwd', 8);
    Print('**** Unix result: \[$G_Var1\] ****');
    log returns as such:
    ==================
    PRINTFN     5/12/2008 11:59:10 AM     **** Unix result:       0:  ****   (--> although 0 but can't see any return pwd result)
    I have tried several versions such as using just sh instead of full path /usr/bin/sh, but also can't work.
    B) For the wait_for_file function, the script is:
    wait_for_file('/source/data/dummy.txt', 0, 0, 1, $G_Path_Filename);
    print('**** Source file and path is = \[$G_Path_Filename\] ****');
    (--> nothing return for the global variable)
    Please advice and thank you.

    Hi,
    I found out one peculiar behavior regarding to Unix delete command of 'rm'.
    My goal is to delete some files using '*.txt' wildcard in Unix command.
    I could perform all following shell scripts at Unix level successfully, but just can't find a way to use the method inside exec function.
    The differrent ways that I had tried out:
    1) exec('rm', '-f *.txt', 0);                -
    > no effect, doesn't work.
    2) exec('rm', '-f `ls *.txt`', 0);          -
    > no effect, doesn't work.
    3) exec('rm', '-f data.txt', 0);          -
    > It worked, but I want to delete few files of type txt, not just one specific file.
    Please advice is it a bug some where?
    Edited by: Chow Ming Darren Cheeng on Dec 9, 2008 3:10 AM

  • Need to execute SQL PLUS commands from C# code

    Hello all,
    This is my first question here and hopefully I will get my solution :)
    Right now we are doing 3 tasks manually
    1) Clearing everything from a DB.
    We use sql plus and execute this :
    RAMNIVAS_CI/RAMNIVAS_CI@orclwex3
    set pages 0
    set lines 80
    spool c:\delete_objects_CI
    select 'drop '||object_type||' '||object_name||';'
    from user_objects;
    spool off
    start c:\delete_objects_CI.lst
    purge recyclebin;
    set pages 100
    select count(*) from user_objects;
    RAMNIVAS_CI/RAMNIVAS_CI@orclwex3 are the username and pwd which gets input when we paste entire thing in sql plus
    2) Then we restore that DB again using sql plus to do it using the command:
    imp file=CL.DMP log=CL.log buffer=1000000 fromuser=RAMNIVAS_CL touser=RAMNIVAS_CL statistics=none grants=n commit=y
    3)Execute sql scripts on it using sql developer. (This is not hard I guess coz I know we can use oracle client)
    4) Take backup using this command:
    exp RAMNIVAS_CI/RAMNIVAS_CI@ORCLWEX3 file=CI.dmp log=CI.log direct=y compress=y buffer=1000000 grants=n statistics=none
    Is there anything I cna do to execute SQL PLUS commands using c#?

    Hi,
    You can execute OS commands via the SHELL function provided in .NET. See the MSDN for more info.
    Some of the things you can do directly from .NET via ODP and PLSQL, some not.
    1) Dropping the user objects can be done via a plsql procedure where you open a cursor for "select 'drop '||object_type||' '||object_name||';' ..." and then use EXECUTE IMMEDIATE to execute the resulting commands. You can invoke the procedure via ODP.
    2) IMP is an exe, not a sqlplus command, so you're not actually using sqlplus there. You can still use the SHELL command though to invoke that.
    3) Executing SQL Scripts via ODP.NET is not something you can do very easily. If you search the threads here you should be able to find some solutions others have come up with to parse the file and execute the statements one by one, but there's nothing built in to ODP to execute a script file.
    You may want to just shell out to sqlplus user/pwd@db @scriptfile.sql but you may have issues trying to track down errors if any occurred, as I'm not sure where they go in that case.
    4) just as with IMP, EXP is an exe, so you could shell out to that.
    Corrections/comments welcome.
    Greg

  • Executing Sql* plus commands

    Hi
    Can we execute SQL *plus commands using JDBC OCI Driver. If so What is the procedure to execute and Which parameters to be set
    With Regards
    Vara Prasad

    AFAIK: no, you can't. SQL*plus is kind of a shell (the worst one I've seen so far), so via JDBC (both OCI and thin), you lack the interpreter.

Maybe you are looking for

  • Just installed security update 2014-002, now Itunes will not open. Have rstrated but no change, need help to fix, please

    Just installed security update 2014-002, now Itunes will not open, I have rebooted twice with no effect, I don't know what else to do to get my itunes back. Need help please

  • How to write a (g)zip file to disk using NIO

    Hi, I want to write some data to a zipped file. I have all data to write to disk in ByteBuffer objects so I want to use NIO. The GZIPOutputstream does not have a getChannel() method. So what is the best method to zip data to file? Any comments are we

  • How to make cell editable alv in WebDynpro for ABAP?

    I make Column editable ALV.(See under source code) But I can't make Cell editable ALV. How to make Cell editable ALV in WebDynpro for ABAP? and..how to get changed data? DATA: l_value TYPE REF TO cl_salv_wd_config_table.   l_value = l_ref_interfaceco

  • Java interpreating problem

    I am using java 4 version the problem is :when i want to run any class file then is send a exception class not found so i am using to avoid this way java MyFile // ERROR java -classpath current_dir MyFile //CORRECT How i avoid to use of -classpath He

  • My DW will not launch.

    This is a Creative Cloud download. windows7, DWCS6 It produces the error code: while executing onLoad in businesscatalyst.htm the following javascript error occured: In file BusinessCatalyst init is not defined. Any ideas. Aside: when this first happ