0

I want to run nm command in linux through java.

I tried this code :

command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(command);

But it's not working, what is wrong with the code?

Rich
  • 5,603
  • 9
  • 39
  • 61
Ashish
  • 1,527
  • 4
  • 17
  • 33

3 Answers3

4

That is not an executable, it is in fact a shell script.

If you invoke the shell with -c, then you can execute your command:

/bin/sh -c "command > here"
Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
2

Here's what you need to do:

String command = "nm -l file1.o > file1.txt";
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});

The following "simple answer" WON'T WORK :

String command = "/bin/sh -c 'nm -l file1.o > file1.txt'";
Process p = Runtime.getRuntime().exec(command);

because the exec(String) method splits its the string naively using whitespace as the separator and ignoring any quoting. So the above example is equivalent to supplying the following command / argument list.

new String[]{"/bin/sh", "-c", "'nm", "-l", "file1.o", ">", "file1.txt'"};
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • how we can get the output of this command? when we using sh it opens new shell, how we can capture the output of command? – Mohse Taheri Apr 28 '15 at 15:56
0

An alternative to pipe would be to read the stdout of your command, see Java exec() does not return expected result of pipes' connected commands for an example.

Instead of redirecting the output using "> file.txt" you would read whatever the output is and write it to a StringBuffer or OutputStream or whatever you like.

This would have the advantage that you could also read stderr and see if there were errors (like no space left on device etc.). (you can also do that using "2>" using your approach)

Community
  • 1
  • 1
PhilW
  • 741
  • 6
  • 23