Colin747
Colin747

Reputation: 5023

Running Linux command from Java - runtime.exe

I'm trying to run the following command using Java runtime:

find /home/Alison/workspace/FunctionalTestFramework/src/com/q1labs/qa/selenium/screens -type d |   awk -F/ 'NF <= old_NF {print prev} {old_NF=NF; prev=$0} END {print $0}'

The command works fine when entered directly into a Terminal but when ran in the following function it gives the following error:

find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Process exitValue: 1

The Java function:

     try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("find /home/Alison/workspace/FunctionalTestFramework/src/com/q1labs/qa/selenium/screens -type d |   awk -F/ 'NF <= old_NF {print prev} {old_NF=NF; prev=$0} END {print $0}'");
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ( (line = br.readLine()) != null)
                System.out.println(line);
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t)
          {
            t.printStackTrace();
          }

Upvotes: 4

Views: 2731

Answers (2)

As I commented, you could exec a shell, e.g. /bin/sh with -c followed by the string to interpret. This is what the system(3) function in standard C does on Unix & Posix systems.

However, I would just suggest to write a shell script doing what your complex command does, and exec that shell script. This gives the ability to (test and to) improve that shell script without changing your Java code.

Upvotes: 3

aymeric
aymeric

Reputation: 3895

Try replacing:

rt.exec("find /home/Alison/workspace/FunctionalTestFramework/src/com/q1labs/qa/selenium/screens -type d |   awk -F/ 'NF <= old_NF {print prev} {old_NF=NF; prev=$0} END {print $0}'");

by this:

rt.exec(new String[]{"find", "/home/Alison/workspace/FunctionalTestFramework/src/com/q1labs/qa/selenium/screens", "-type", "d"});

Note that you will not be able to run any command that uses a pipe | because redirection operators like pipes are a shell feature, but the command passed to exec() isn't run in a command shell.

Upvotes: 0

Related Questions