1

I'm trying to execute a command:

public static void main(String[] args) { int buffer; StringBuilder res = new StringBuilder(); Process proc; try { proc = Runtime.getRuntime().exec("cat /proc/stat | grep 'btime' | awk '{print $2}'"); BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String line; while ((line=reader.readLine())!=null) { System.out.println(line); } proc.waitFor(); } catch (Exception e) { e.printStackTrace(); } } 

But the result is not what I expected:

cat: '|': No such file or directory cat: grep: No such file or directory cat: "'btime'": No such file or directory cat: '|': No such file or directory cat: awk: No such file or directory cat: ''\''{print': No such file or directory cat: '$2}'\''': No such file or directory 

What am I doing wrong? Ubuntu 18.04.

2
  • Runtime.exec cannot run arbitrary shell/terminal commands like this. Commented Nov 17, 2018 at 16:49
  • Possible duplicate of: stackoverflow.com/questions/15356405/… Commented Nov 17, 2018 at 16:52

1 Answer 1

2

Runtime.exec cannot run arbitrary shell/terminal commands like this.

You have to run the bash program and then send your command as parameter to bash. Bash will do the job for you.

https://stackoverflow.com/a/15356451/1364747

This is OS specific. On a different OS it might be a different command/terminal. Also you might need to know the path to that program.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.