Cygwin bash using ProcessBuilder

Hi,
i am trying to execute a command in a cygwin-bash.
the java code is:
import java.io.*;
public class cmd {
     public static void execute(String cmd_array[]) {
          execute(cmd_array, null);
     public static void execute(String cmd_array[], String work_directory) {
          try {
               ProcessBuilder pb = new ProcessBuilder(cmd_array);
               if(work_directory != null) {
                    pb.directory(new File(work_directory));
               Process process = pb.start();
               String line;
               System.out.println("Here is the standard output of the command:\n");
               BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
               while ((line = stdInput.readLine()) != null) {
                    System.out.println(line);
               System.out.println("Here is the error output of the command:\n");
               BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
               while ((line = stdError.readLine()) != null) {
                    System.out.println(line);
               process.waitFor();
               System.out.println(process.exitValue());
          } catch(IOException e) {
               e.printStackTrace();
          } catch(InterruptedException e) {
               e.printStackTrace();
}the following is working:
String[] cmd_array = new String[2];
cmd_array[0] = "C:/Program Files/System/Cygwin/bin/bash.exe";
cmd_array[1] = "--version";
cmd.execute(cmd_array,"C:/Program Files/System/Cygwin/bin");this does not work:
String[] cmd_array = new String[3];
cmd_array[0] = "C:/Program Files/System/Cygwin/bin/bash.exe";
cmd_array[2] = "--login";
cmd_array[2] = "-c 'ls'";
cmd.execute(cmd_array,"C:/Program Files/System/Cygwin/bin");i get the following output:
Here is the standard output of the command:
Here is the error output of the command:
/usr/bin/bash: - : invalid option
Usage:  /usr/bin/bash [GNU long option] [option] ...
        /usr/bin/bash [GNU long option] [option] script-file ...
GNU long options:
        --debug
        --debugger
        --dump-po-strings
        --dump-strings
        --help
        --init-file
        --login
        --noediting
        --noprofile
        --norc
        --posix
        --protected
        --rcfile
        --restricted
        --verbose
        --version
        --wordexp
Shell options:
        -irsD or -c command or -O shopt_option          (invocation only)
        -abefhkmnptuvxBCHP or -o optionIt seems as if the argument --login is not passed correctly.
Thanks for any help.
Robert

Hi,
i am trying to execute a command in a cygwin-bash.
the java code is:
import java.io.*;
public class cmd {
     public static void execute(String cmd_array[]) {
          execute(cmd_array, null);
     public static void execute(String cmd_array[], String work_directory) {
          try {
               ProcessBuilder pb = new ProcessBuilder(cmd_array);
               if(work_directory != null) {
                    pb.directory(new File(work_directory));
               Process process = pb.start();
               String line;
               System.out.println("Here is the standard output of the command:\n");
               BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
               while ((line = stdInput.readLine()) != null) {
                    System.out.println(line);
               System.out.println("Here is the error output of the command:\n");
               BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
               while ((line = stdError.readLine()) != null) {
                    System.out.println(line);
               process.waitFor();
               System.out.println(process.exitValue());
          } catch(IOException e) {
               e.printStackTrace();
          } catch(InterruptedException e) {
               e.printStackTrace();
}the following is working:
String[] cmd_array = new String[2];
cmd_array[0] = "C:/Program Files/System/Cygwin/bin/bash.exe";
cmd_array[1] = "--version";
cmd.execute(cmd_array,"C:/Program Files/System/Cygwin/bin");this does not work:
String[] cmd_array = new String[3];
cmd_array[0] = "C:/Program Files/System/Cygwin/bin/bash.exe";
cmd_array[2] = "--login";
cmd_array[2] = "-c 'ls'";
cmd.execute(cmd_array,"C:/Program Files/System/Cygwin/bin");i get the following output:
Here is the standard output of the command:
Here is the error output of the command:
/usr/bin/bash: - : invalid option
Usage:  /usr/bin/bash [GNU long option] [option] ...
        /usr/bin/bash [GNU long option] [option] script-file ...
GNU long options:
        --debug
        --debugger
        --dump-po-strings
        --dump-strings
        --help
        --init-file
        --login
        --noediting
        --noprofile
        --norc
        --posix
        --protected
        --rcfile
        --restricted
        --verbose
        --version
        --wordexp
Shell options:
        -irsD or -c command or -O shopt_option          (invocation only)
        -abefhkmnptuvxBCHP or -o optionIt seems as if the argument --login is not passed correctly.
Thanks for any help.
Robert

Similar Messages

  • Exception "Cannot run program" while using ProcessBuilder class

    Hi Java-Folks,
    I try to start a program within a Java application using the ProcessBuilder class. This is the first time I use ProcessBuilder so I do not have any deep knowledge of it. Here is a snippet of my code:
    static void connectToHost(String Host) {
    ProcessBuilder pb = new ProcessBuilder("connect.exe"), Host);
    Map<String, String> env = pb.environment();
    env.put("SHELLWIDTH", "64");
    pb.directory(new File("C:\\MyProgram\\ExApp\\shell"));
    try (
    Process p = pb.start();
    } catch (IOException ex) {
    Logger.getLogger(ShellUtil.class.getName()).log(Level.SEVERE, null, ex);
    }Using this method I get an IOException which says *"Cannot run program "connect.exe" (in directory "C:\MyProgram\ExApp\shell"): CreateProcess error=2, The system couldn't find the specified file"*
    Does anybody have an idea why this is not working? I tried to start another application like "notepad.exe" and that works fine. So it seems related to the fact
    that the program I want to start is only available in a certain directory and not via the PATH env-variable.
    I would appreciate any help or hint :-)
    Regards,
    Lemmy

    Okay I guess I misinterpreted the JavaDocs regarding the directory method. The exception message is a little bit confusing too, because it seems like Java tries to find the Application within the specified
    working directory.
    I tried to use the full path with the ProcessBuilder constructor and it looks like this variant is working. I still have some trouble with the application itself but I was able to start another program which is
    not in the PATH var, using the full path to the executable.
    Thanks for the help so far.
    Bye
    Lemmy

  • Using ProcessBuilder

    Hi All,
    I am using ProcessBuilder in my java code to execute a perl script. The perl script sets up a server using the following code:
    $server = IO::Socket::INET->new( Proto => 'tcp',
    LocalPort => $PORT,
    Listen => SOMAXCONN,
    Reuse => 1);
    die "Can't setup server\n" unless $server;
    I get "Cannot setup server" message error message. The perl script runs fine and sets up a server successfully when run from the terminal. However when ProcessBuilder runs this script I get "Cannot setup server" error message. Before running the java code, I assured that the port the perl script uses is not in use.
    Is it that I cannot do this with ProcessBuilder?
    Can anyone please suggest a remedy/alternative to do this
    Thanks,
    Akhil

    I am posting my reply again in a more readable form.
    Here, is my simple Java code that forks a perl script named charniak-parser.pl
    public class MyClass {
             public static String runProcess(List<String> command, java.util.Map<String, String> env) throws Exception {
                            ProcessBuilder pb = new ProcessBuilder(command);
                            pb.redirectErrorStream(true);
                            if(env.size() != 0){
                                     java.util.Map<String, String> environment = pb.environment();
                                     environment.putAll(env);
                            Process p = pb.start();
                            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                            StringBuilder sb= new StringBuilder();
                            String line;
                            while((line = br.readLine())!=null){
                                     sb.append(line '\n');
                            p.waitFor();
                            return sb.toString();
               public static void main(String[] args){
                           java.util.HashMap<String, String> env = new java.util.HashMap<String, String>();
                           env.put("CHARNIAK", "project/akhil/srl/CharniakServer/parser05May26fixed");
                           String message = runProcess(Arrays.asList("nohup", "/project/akhil/srl/CharniakServer/charniak-server.pl", "&>", "charniak-server.log", "&"), env);
                           System.out.println("message: " message);
    }In the above code, I have set up an environment variable that is required by the perl script in it's execution.
    Here, is the beginning code of my perl script (charniak-parser.pl):
    #!/usr/bin/perl
    $MAXCHAR = 799;
    $MAXWORD = 400;
    $charniakDir = "$ENV{CHARNIAK}";
    $command = "$charniakDir/PARSE/parseIt $charniakDir/DATA/EN/ -K -l$MAXWORD";
    #$endProtocol = "\n\n\n";
    $endProtocol = "\n";
    $TIMEOUT = 60; # undef if no timeout
    $PORT = 4449; # pick something not in use
    #read port
    $PORT = $ARGV[0] if (scalar(@ARGV) > 0);
    use Expect;
    #create main program that will be communicating throught pipe.
    $main = NewExpect($command);
    sub NewExpect {
        my $command = shift;
        my $main;
        print "[Initializing...]\n";
        $main = new Expect();
        $main->raw_pty(1); # no local echo
        $main->log_stdout(0); # no echo
        $main->spawn($command) or die "Cannot start: $command\n";
        $main->send("<s> This is a test . </s>\n"); #send input to main program
       @res = $main->expect(undef,$endProtocol); # read output from main program
        print "[Done initializing.]\n";
        return $main;
    #server initialization matter
    use IO::Socket;
    use Net::hostent; # for OO version of gethostbyaddr
    $server = IO::Socket::INET->new( Proto => 'tcp',
                                                        LocalPort => $PORT,
                                                        Listen => SOMAXCONN,
                                                        Reuse => 1);
    die "Can't setup server: $! " unless $server;
    #end server initializationThe output of the java program is :
    [Initializing...]
    [Done initializing.]
    Can't setup server:Before running the code, I always assure that the port 4449 is free.
    If more information required, please let me know.
    Akhil

  • Use ProcessBuilder to execute a java program with a file piped as input

    Hi,
    I am trying to execute a java program passing in input file as argument. I have to do this by forking a process and am using Processbuilder.
    I have a main function which calls the executeCliTopologyDesigner method. I get a Java I/O exception
    Caught IOException: Cannot run program "$JAVA_HOME/bin/java oracle.apps.fnd.provisioning.cli.TopologyDesigner ": java.io.IOException: error=2, No such file or directory
    Can you please let me know if I am missing something?
    Thanks,
    pkrish
    Code Snippet:
    private synchronized void executeCliToplogyDesigner(String cliCommand, File tmp)
    throws IOException, InterruptedException
    {    File temp= writeDataInTemp(compDefName);
    cliCommand = "$JAVA_HOME/bin/java oracle.apps.fnd.provisioning.cli.TopologyDesigner ";
    ProcessBuilder pb = new ProcessBuilder(cliCommand,"<",temp.getCanonicalPath());
    executeProcess(pb);
    Edited by: pkrish on Mar 2, 2009 3:56 PM
    Edited by: pkrish on Mar 2, 2009 3:57 PM
    Edited by: pkrish on Mar 2, 2009 3:58 PM
    Edited by: pkrish on Mar 2, 2009 3:59 PM

    Hi,
    I printed out the system environment variables PATH and CLASSPATH and it is as below:
    Classpath :/ade/prprasa_prov_latest/fmwtest/tools/orajtst/home/lib/orajtst.jar:/ade/prprasa_prov_latest/jdev/src/abbot/dist/EXTENSIONS
    Path :/ade/prprasa_prov_latest/fxtn/util/tools/ant/bin:/ade/prprasa_prov_latest/fmwtest/tools/orajtst/home/bin:/ade/prprasa_prov_latest/oracle/jdeveloper/jdev/bin:/ade/prprasa_prov_latest/javahome/jdk/bin:/usr/kerberos/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/usr/local/ade/bin:/OracleProd/oracle10g/bin:/OracleProd/oracle10g/bin:/OracleProd/oracle10g/bin
    The Path does contain java.
    I changed my command as I need a different classpath.
    cliCommand = "/ade/prprasa_prov_latest/javahome/jdk/bin/java -classpath .:/ade/prprasa_prov_latest/oracle/provisioning/tools/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/configframework/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/framework/lib/*"
    Caught IOException: Cannot run program "/ade/prprasa_prov_latest/javahome/jdk/bin/java -classpath .:/ade/prprasa_prov_latest/oracle/provisioning/tools/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/configframework/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/framework/lib/*": java.io.IOException: error=2, No such file or directory
    Any ideas? Please let me know where do I post it if not here.

  • Using ProcessBuilder to execute multiple commands.

    I am having issues getting ProcessBuilder to execute multiple commands in windows.
    As an example I would like to execute "dir /w" fallowed by "java.exe some.App arg1 arg2".
    I can accomplish this from the command line by using "&".
    Example: dir /w & java.exe some.App arg1 arg2 Or: dir /w & dir /c"
    For internal commands (i.e. dir and cd) I know that commands in the array being passed to ProcessBuilder must be formatted like {"dir /w", "dir /c"}
    see post: [http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html]
    Here is an example of one of the many things I have tried:
    {code}
    String[] commands = new String[]{"dir /w", "&", "java.exe", "some.App", "arg1", "arg2"};
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.start();
    {code}
    Any other ideas / what am I doing wrong?
    Edited by: brianjbrady on May 7, 2009 4:49 PM
    Edited by: brianjbrady on May 7, 2009 4:50 PM

    brianjbrady wrote:
    You can run dir all day long without using cmd.exe. Try it. It works for me.Perhaps you have cygwin in your path.
    How are you running dir out of interest (and don't say with a DOS window ;)
    import java.io.*;
    import java.util.Arrays;
    public class Main {
        public static void main(String... args) throws IOException {
            run("dir");
            run("dir.exe");
            run("cmd", "/c", "dir");
            run("c:\\cygwin\\bin\\dir");
        private static void run(String... command) throws IOException {
            try {
                ProcessBuilder pb = new ProcessBuilder(command);
                pb.redirectErrorStream(true);
                Process p = pb.start();
                InputStream is = p.getInputStream();
                System.out.println("\nCommand " + Arrays.asList(command) + " reported");
                int b;
                while ((b = is.read()) >= 0)
                    System.out.write(b);
                is.close();
                p.destroy();
            } catch (IOException e) {
                System.err.println("\nCommand " + Arrays.asList(command) + " reported " + e);
    }Prints
    Command [dir] reported java.io.IOException: Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified
    Command [dir.exe] reported java.io.IOException: Cannot run program "dir.exe": CreateProcess error=2, The system cannot find the file specified
    Command [cmd, /c, dir] reported
    Volume in drive D is Work Disk
    Volume Serial Number is AC0B-0757
    Directory of D:\dev\scratch
    26/12/2008  22:15    <DIR>          .
    26/12/2008  22:15    <DIR>          ..
    03/09/2007  21:45    <DIR>          classes
    26/08/2008  20:14            65,280 mynamedpipe
    23/11/2008  11:37           201,354 name.ppt.txt
    24/10/2008  20:00           201,354 race.txt
    05/11/2008  23:17         6,193,334 record.csv
    08/01/2009  16:44               704 scratch.iml
    27/12/2008  12:29            21,576 scratch.ipr
    08/05/2009  20:02            53,258 scratch.iws
    28/04/2009  21:34    <DIR>          src
    07/12/2008  11:44               101 test.txt
                   8 File(s)      6,736,961 bytes
                   4 Dir(s)  32,506,023,936 bytes free
    Command [c:\cygwin\bin\dir] reported
    classes      name.ppt.txt  record.csv     scratch.ipr  src
    mynamedpipe  race.txt        scratch.iml     scratch.iws  test.txt

  • Unable to use ProcessBuilder on Vista, Works on Linux, XP, etc

    Hello, I support an application on many different platforms, and I am running into a problem with Vista. The code works on every combination I have tested (Mac, Linux, various flavors of Windows) except MS Vista and IE7. It even works on both WinXP and IE7 and MS VIsta and Firefox. Unfortunately this is old code and I didn't write it so I'm not sure what to do. It was using RunTime.exec() and I updated it to ProcessBuilder.start() but it has the same symptoms. The symptoms are that instead of the input and output being redirected, a console window is launched and used instead.
    String command = slaunch + " " + appName + " " + app + " " + _debug;
    Process p = new ProcessBuilder(command.split(" ")).start();
    BufferedInputStream stdout = new BufferedInputStream(p.getInputStream());
    BufferedInputStream stderr = new BufferedInputStream(p.getErrorStream());
    boolean keeprunning = true;
    String out = "";
    String err = "";
    int exitvalue = 0;
    while(keeprunning) {
    try {
    exitvalue = p.exitValue();
    keeprunning = false;
    Thread.sleep(300);
    } catch(IllegalThreadStateException itse) {}
    try { Thread.sleep(100); } catch(Exception e) {}
    int available = stdout.available();
    if(available > 0) {
    byte[] buf = new byte[available];
    stdout.read(buf);
    out = out + new String(buf);
    Any help would be greatly appreciated. I am very tempted to tell my Vista users to just use Firefox, but that would go over like a lead balloon.
    James

    Also, your current code is weird. See below.
    public class Bear{
      public void method(){
        String command = slaunch + " " + _appName + " " + _app + " " + _debug;
        Process p = new ProcessBuilder(command.split(" ")).start();
        BufferedInputStream stdout = new BufferedInputStream(p.getInputStream());
        BufferedInputStream stderr = new BufferedInputStream(p.getErrorStream());
        boolean keeprunning = true;
        String out = "";
        String err = "";
        int exitvalue = 0;
        while (keeprunning) { // ????? what's the sense of it?
          try {
            exitvalue = p.exitValue(); // use waitFor() instead
            keeprunning = false; // ?????
            Thread.sleep(300); // ?????
          catch (IllegalThreadStateException itse) {
          try {
            Thread.sleep(100); // ?????
          catch(Exception e) {
          int available = stdout.available(); // never use available()
          if(available > 0) { // ????? no use
            byte[] buf = new byte[available];
            stdout.read(buf);
            out = out + new String(buf);
    //--- a standard code ----
          String line;
          try {
            BufferedReader br
             = new BufferedReader(new InputStreamReader(p.getInputStream()));
            exitvalue = p.waitFor();
            while ((line = br.readLine()) != null){
              out += line;
          catch(Exception e) {
            e.printStackTrace();
    //-------------------------

  • Want my client to shutdown the PC using processbuilder!

    Hey All
    I'm working on a Java server and client. Right now i can send my Client strings using sockets and stream readers and writers. Once the Client recieves this string I place it in a processbuilder function and have it execute the "command" it haas been given, a simple example would be the server sending the client the string "calc" and the client executing "calc" to open the calculator.
    My problem is when i send the client a String such as "shutdown -r" to shutdown and restart the client, my client throws an IOException.
    Does anyone have any ideas how I can implement a hardware shutdown, do I need to grant the client special permissions to implment critical commands?
    Thanks in advance
    rev

    http://www.google.com/search?q=shutdown+windows+from+java

  • [SOLVED][BASH] Using a string to pass multiple arguments.

    I'm scratching my brain on this little project my friend roped me into.
    I have a function which generates a list of VM's and their states and stores it as a variable. this list is to be presented to the user using the libgui.sh 'ask_option' function. The problem is that the ask_option function does not interpret it correctly. And by saying ask_option isn't doing it right I mean I am expecting a certain behavior, and that expectation is flawed.
    Here are the two parts in question
    #assume VMLIST has a value identical to this assignment after my function call:
    #I have confirmed that this is the exact value
    VMLIST="\"Arch Linux Live\" \"running\" \"Windows XP\" \"power off\""
    ask_option 0 "VMs Present" '' optional "0" "Return to the Main Menu" $VMLIST
    What I actually get shows that ask_option is interpreting each discreet word as an argument. whereas I want the argument to be the text between each quote
    0 Return to Main Menu
    "Arch Linux
    Live" "running"
    "Windows XP"
    "power off"
    Obviously what I want is a two column output in the dialog that resembles
    0 Return to Main Menu
    Arch Linux Live running
    Windows XP power off
    What should our approach be to rectify this? How can I use the variable to suppply discreet arguments to another function? or rather how can I have the value of the variable interpreted literally on the function call line?
    Last edited by OrionFyre (2011-04-05 19:04:49)

    ARRAYS! I knew that
    Thanks scary face kitteh!
    I should have remembered arrays. alas. that's what happens when you don't use it for a while.

  • /bin/bash uses shared libs

    Not sure if this is an actual problem per se, but I had a file system problem on my box which meant I needed to run fsck on 2 partitions (/usr and /home).  So I ran 'init s' and umounted /home no probs but could not umount /usr as bash needed a few libs from /usr/lib.
    This meant that I had to dig out a rescue disk and boot from that to run fsck.
    Wouldn't it make sense to have bash built with these libs built in so that this dependancy wasn't an issue?

    http://aur.archlinux.org/packages.php?ID=22650

  • Bash: Use command output as argument for next command in pipe

    I'm trying to do this:
    tail -f /var/logfile | grep -C 0 text | mail -s "OUTPUT OF GREP" [email protected]
    How can I do this?

    Haven't tested it but try
    mail -s $(tail -f /var/logfile | grep -C 0 text) [email protected]
    Edit: Are you sure it will work with 'tail -f'?
    Seems that the subject can't contain certain characters:
    [karol@black ~]$ mail -s $(tail /var/log/kernel.log | grep -C 0 detected) [email protected]
    18:05:11 contains invalid character ':'
    kernel: contains invalid character ':'
    [ contains invalid character '['
    8.433910] contains invalid character ']'
    4-0:1.0: contains invalid character ':'
    ^C
    How will you escape multiple newlines?
    Last edited by karol (2011-05-20 15:20:07)

  • Using bash to import/export from qt

    i have an operation i perform repeatedly and would like to write
    a bash script to do it automatically.
    what i'd like to do is:
    1. open an image sequence in qtplayer
    2. file--->export
    3. set options (like custom size, what codec)
    4. save the export as the same filename as the first file of the image sequence
    can this be done via bash?
    can anyone point me to some info on passing parameters to qtplayer via bash?
    thanks,
    BabaG

    Have you tried using Applications -> Automator -> Record and then let Automator record steps you want to do. If that works, it would be the easiest way to automate this.
    If you want to invoke the Automator script you can use the open command from within bash
    If Automator -> Record does not work for you needs, then an Applescript is the next thing you should try. If you want to invoke this from bash use the osascript command.
    Applescript questions would be best asked in the Apple Applescript forum <http://discussions.apple.com/forum.jspa?forumID=724>
    If you want/need more bash shell script questions answered, the Apple Unix forum would be the best bet <http://discussions.apple.com/forum.jspa?forumID=735>
    And while I'm mentioning the open command, you can start *QuickTime Player* with a specific file usng open
    open -a /Applications/QuickTime Player.app file.jpg
    Where file.jpg could be any file that *QuickTime Player* knows how to handle.
    Steps 2, 3, & 4 are operations that would be better handled via Automator or Applescript.

  • Using Bash script to edit config file

    This is a really simple question, but given that I'm just learning Bash scripting and having this solved now would be really illustrative for me, I would really thank some help here.
    I'm using uzbl, and running Tor+Polipo. So, as you will see below in the tail of the config file, there is a line to redirect the requests of uzbl through Polipo.
    # === Post-load misc commands ================================================
    sync_spawn_exec @scripts_dir/load_cookies.sh
    sync_spawn_exec @scripts_dir/load_cookies.sh @data_home/uzbl/session-cookies.txt
    # Set the "home" page.
    #set uri = https://duckduckgo.com
    # Local polipo proxy
    set proxy_url = http://127.0.0.1:8123
    # vim: set fdm=syntax:
    What I want to accomplish is to comment in/out that line with a key shortcut on Awesome. I've thought of doing 2 scripts to do so and using 2 differente key shortcuts, but I want to "toggle" the proxy redirection with only 1 shortcut. To do so, I suppose that the script should go something like:
    if
    tool 'set proxy_url = http://127.0.0.1:8123' config_file
    then
    tool '#set proxy_url = http://127.0.0.1:8123' config_file
    else
    if
    tool '#set proxy_url = http://127.0.0.1:8123' config_file
    then
    tool 'set proxy_url = http://127.0.0.1:8123' config_file
    fi
    fi
    I know little about sed, but I think is the tool for this job. The most intriging part to me is to ask sed to print the regular expression when it finds it in the config file, and use that as an input in the conditional statement.
    Well, this is a mess I have done here. Hope there is a simple answer to this.
    Thanks in advance.-

    You can do this with a single sed command:
    sed -i 's/^#set proxy_url/set proxy_url/;
    t end;
    s/^set proxy_url/#set proxy_url/;
    : end' config_file
    This edits the file in-place (-i) and first tries to replace the commented with the uncommented line. If that suceeds, sed jumps to the "end" label. If not, it tries to replace the uncommented with the commented line. Thus you don't have to include any logic about the current state: if the first substitution succeeds, the line was obviously commented, if not, it was uncommented, and the second substitution should succeed.
    Note that my knowledge of sed is very limited. There might be a simpler way to do this.
    EDIT: For the sake of example, here's how to do the same in bash using regular expressions. Note how this script needs to use a temporary file to simulate in-place editing, how it needs to process the file line by line manually, etc. All things that sed does out of the box...
    #!/bin/bash
    tmp=test.conf.tmp
    echo -n "" > "$tmp"
    while read line; do
    if [[ "$line" =~ ^#set\ proxy ]]; then
    echo "${line/\#/}" >> "$tmp"
    elif [[ "$line" =~ ^set\ proxy ]]; then
    echo "#$line" >> "$tmp"
    else
    echo "$line" >> "$tmp"
    fi
    done < test.conf
    mv test.conf.tmp test.conf
    To answer your original question, the line
    if [[ "$line" =~ ^#set\ proxy ]]; then
    reads: if the line begins with a "#", followed by "set proxy", then...
    Last edited by hbekel (2011-03-20 10:40:16)

  • Any tips on Controlling interactive bash shell on Cygwin via Java process?

    Ideally, I'd like to be able to control an interactive bash shell on Cygwin from a Java process. But for starters, I want to do 'ls > /cygdrive/c/fred.txt'. The little program to do this, below, doesn't work. It simply runs without error.
    Any ideas? And also, any tips on doing a fully interactive shell?
    --> Java program to test simple command:
    package com.treelogic_swe.real_estate_explorer.utils;
    import java.io.File;
    import java.io.InputStream;
    * Quick and dirty test of Java to Cygwin bash shell process control.
    * Thanks to [email protected]
    * re: http://groups.google.com/group/comp.lang.java.help/browse_thread/thread/914403fbdd1de127/40363d2e7cbae823?lnk=st&q=cygwin+shell+java+process+runtime&rnum=1&hl=en#40363d2e7cbae823
    public class RunSystemCommand {   
        public static void main(String args[]) throws Throwable {
         // System command to run
         String cmd = "ls > /cygdrive/c/fred.txt";
            String [] sysArgs = { };
         // Set the working directory for the OS command processor
         File workDir = new File( "c:/cygwin/bin" );
         Process bash = Runtime.getRuntime().exec( cmd, sysArgs, workDir );
         InputStream bashIn = bash.getInputStream();
         while( bashIn.read() != -1 ); // Added, as otherwise the ls hangs.
         bash.waitFor();
    }

    Ideally, I'd like to be able to control an
    interactive bash shell on Cygwin
    What do you mean by this? Do you just want to start a bash shell, and have it's input and output come from and go to your Java program?
    Please be specific about what you want, as there are a couple of interpretations for what you said. You need to understand the differences and relationships among terminals, shells, shell builtins, and executables.
    You'll want to read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    from a Java
    process. But for starters, I want to do 'ls >
    /cygdrive/c/fred.txt'. The little program to do
    this, below, doesn't work. It simply runs without
    error.
    , <, |, and others are specific to the shell. When you're in a terminal, and you type ls > /tmp/zzz, it's the bash shell that interprets the >. Cygwin doesn't know anything about it. ls doesn't know anything about it.So if you want to to that, the command you'd execute from Java is not ls, but bash (or some other shell). You'd then tell bash to execute the rest. I'm not sure what the command line arg is for bash to tell it the rest of the command line args are a command that bash should interpret and execute. I think it might be -c like it is for zsh. So you'd need to do something like Runtie.getRuntime().exec("bash -c 'ls > /tmp/zzz'");

  • Bash CVE-2014-6271 Vulnerability

    Excuse me if this was already posted. I searched title's only for bash and 6271 and didn't see any results.
    Cut and paste from CVE-2014-6271 Bash vulnerability allows remote execution arbitrary code:
    This morning a flaw was found in Bash with the way it evaluated certain environment variables. Basically an attacker could use this flaw to override or bypass environment restrictions to execute shell commands. As a result various services and applications allow remote unauthenticated attackers to provide environment variables, allowing them to exploit this issue.
    Details on CVE-2014-6271 from the MITRE CVE dictionary and NIST NVD (page pending creation).
    I’m currently patching servers for this. The issue affects ALL products which use Bash shell and parse values of environment variables. This issue is especially dangerous as there are many possible ways Bash can be called by applications. Quite often if an application executes another binary, Bash is invoked to accomplish this. Because of the pervasive use of the Bash shell, this issue is quite serious and should be treated as such!
    To test if your version of Bash is vulnerable run the following command:
    env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
    If that command returns the following:
    vulnerable this is a test
    …then you are using a vulnerable version of Bash and should patch immediately. The patch used to fix this issue ensures that no code is allowed after the end of a Bash function. Thus, if you run the above example with the patched version of Bash, you should get an output similar to:
    bash: warning: x: ignoring function definition attempt
    bash: error importing function definition for `x'
    this is a test
    Arch Linux CVE-2014-6271 patch:
    pacman -Syu
    Last edited by hydn (2014-09-28 20:57:41)

    On a related note.  I post this here as it might be of interest to some members....
    I just checked my DD-WRT based router for this vulnerability.   It comes stock with Busybox and does not seem to be vulnerable, but...   I keep bash on a separate partition which gets mounted on /opt.  That bash is vulnerable.  Until the DD-WRT project catches up, I suggest anyone using that router firmware consider disabling Bash for the time being and stick with BB.
    Also, as another aside, ArchArm has this fix in place now and is safely running on my Raspberry Pi.   
    I did kill the ssh service on the Windows Box that let me into bash via Cygwin.  Cygwin Bash is vulnerable as of when I began this post.
    Last edited by ewaller (2014-09-25 18:26:18)

  • How to control (the input and output) EXE file after I call it using exec?

    Hi,
    I knew that I can use runtime.exec() to call one EXE file, and this works. But this EXE has two characteristics:
    1. After this exe starts, it asks user to input number such as 1 or 2 onto computer screen, then press return. Then the exe will start the calculation.
    2. after it starts calculation, it prints 3 columns of numbers onto the screen.
    My two questions are:
    1. How to use java to input the number such as 1 or 2 automatically? this EXE can not work like this in DOS command line:
    C:> file.exe parameter
    The parameter is the number such as 1 or 2 that I wanna input.
    2. how to redirect the 3 columns of numbers from computer screen to txt file?
    My colleague can solve these two questions using Mathematica. So I know that definitely there is at least one solution for it. I just can not do it using Java. This wierd exe file bothered me a lot and I really wish that I can get help from someone in java community.
    Thank you!
    Tony

    When you call Runtime.exec, you get a Process object. (I presume something similar happens when you use ProcessBuilder.) Process has methods with names getOutput, getInput, and getError. These correspond to the standard input, standard output, and standard error streams of the spawned process.
    You can read and write to the process on the streams corresponding to input and output that the process writes to the console.
    [add]
    In fact, you should be grabbing and reading the output/error streams anyway, because of the points raised by the Traps article. Google "Java Runtime exec traps" and you'll probably get a link to this JavaWorld article, which describes common Runtime.exec problems and how to solve them.
    Edited by: paulcw on Jun 15, 2010 4:09 PM

Maybe you are looking for

  • White or black -- heat issues when in the sun??

    I have a black 4s now and I'm deciding between the white and black 5S later this month. I tend to use my phone as my GPS and have a window mount that holds the phone up for me.  However, this means that the back of the phone is frequently in direct s

  • How to cancel update firefox 29.0?

    How to cancel update firefox 29.0? I want back my Firefox 28.0 !

  • Photoshop Crashing during simple tasks

    Hello all, We're having a problem with Photoshop crashing during simple tasks like masking. This is on a Mac Pro 5,1 with a 2.4GHz Xeon, ATI Radeon 5770 Graphics card, and 32GB RAM. Photoshop CC 14.2.0  Here is the error report: Process:         Adob

  • Update options in ui

    hi jdev people., here am using jdev11.1.1.5.0 adfbc. i had af: table in my ui. it had some createinsert,commit,delete operation. what i need? i want to some update operation(button) in my ui. for the purpose updating the existing records. how can i p

  • Lock screens on the Ipad2?

    Is there a way to lock screens on the Ipad 2?  I would like to move my work related apps to a seperate screen that could be password protected so that my pre-schooler can't access by "accident" when playing apps that I have downloaded for him on my I