You need to run it using bash executable like this:
Runtime.getRuntime().exec("/bin/bash -c your_command");
Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
Answer from Rahul on Stack OverflowMedium
beknazarsuranchiyev.medium.com › run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how to… | by Beknazar | Medium
April 24, 2022 - We work on actual execution with Process instance. For example to get the status code from the process, to get its id, to see the output, to wait, and to kill the process. Thank you for reading, have a wonderful day! Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming OS, File, and File System Working with terminal Welcome to Java Programming Language Variables and Primitives in Java Convert String to numeric data type Input from the terminal in Java Methods with Java
Top answer 1 of 6
59
You need to run it using bash executable like this:
Runtime.getRuntime().exec("/bin/bash -c your_command");
Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
2 of 6
23
I vote for Karthik T's answer. you don't need to open a terminal to run commands.
For example,
// file: RunShellCommandFromJava.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunShellCommandFromJava {
public static void main(String[] args) {
String command = "ping -c 3 www.google.com";
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
The output:
$ javac RunShellCommandFromJava.java
$ java RunShellCommandFromJava
PING http://google.com (123.125.81.12): 56 data bytes
64 bytes from 123.125.81.12: icmp_seq=0 ttl=59 time=108.771 ms
64 bytes from 123.125.81.12: icmp_seq=1 ttl=59 time=119.601 ms
64 bytes from 123.125.81.12: icmp_seq=2 ttl=59 time=11.004 ms
--- http://google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.004/79.792/119.601/48.841 ms
Videos
29:56
LaTeX for Java Developers -- Part 11: How to Run Terminal Commands ...
01:31
How to execute linux commands in Java - YouTube
03:34
Run Command Prompt CMD commands from JAVA J2EE projects - YouTube
08:53
How to execute a shell script from Java in Eclipse - YouTube
06:04
How to Execute a shell command Using Runtime.exec - Java - YouTube
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - public Process exec(String command, String[] envp, File dir) - Executes the command, with the specified environment variables, from within the dir directory.
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Here, we created a new sub-process with .newSingleThreadExecutor() and then used .submit() to run our Process containing the shell commands. Additionally, .submit() returns a Future object we utilize to check the result of the process. Also, make sure to call the .get() method on the returned object to wait for the computation to complete. If you are running the above code from a main method, be sure to call shutdown on the executorService object or the code will never stop.
GeeksforGeeks
geeksforgeeks.org › java › how-to-execute-native-shell-commands-from-java-program
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
March 3, 2021 - We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine. ... // Run a simple Windows shell command import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of comm
freeCodeCamp
freecodecamp.org › news › how-to-execute-and-run-java-code
How to Execute and Run Java Code from the Terminal
March 10, 2022 - You can go into the directory where you have kept your source code either by following the typical GUI way or from the terminal using the cd command as well. ... Before running our Java code, we need to compile it first. To compile a Java code/program, we get the class file. Then we need to execute...
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - I am trying to convert avro to json file through java, But it is not working String output = obj.executeCommand(“java -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.json”); But this is not working through java file, I ran same command through terminal, avro is converted to json ... Why commands with pattern don’t work? Example: uptime | sed “s/^.* up \+\(.\+\), \+[0-9] user.*$/\1/” ... Using array parameter is better, because…when some parameter has blank ( ex. “ABC DE” ) it will be treated as 2 parameters… ... Now..How do I do this – execute shell command from java – from in-app text (i.e.
CodingTechRoom
codingtechroom.com › question › execute-terminal-commands-java-program
How to Execute Terminal Commands from a Java Program? - CodingTechRoom
Running terminal commands from a Java program can be achieved using either the `Runtime` class or the `ProcessBuilder` class. Both methods allow you to execute operating system commands and handle input/output streams effectively.
CodeJava
codejava.net › java-se › file-io › execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - For example, the following statements execute a Windows command to list content of the Program Files directory: String commandArray[] = {"cmd", "/c", "dir", "C:\\Program Files"}; Process process = Runtime.getRuntime().exec(commandArray);For other exec() methods, consult the relevant Javadoc which is listed below.
CodingNomads
codingnomads.com › how-to-run-java-from-command-line
Executing Java applications from the CLI
A Java application can be run and compiled from the command line. Although running Java apps from the CLI during normal development is not entirely common, it is essential to know how it is done. Please follow the steps below to run your first Java app from the CLI. First, open your terminal and ...
Coderanch
coderanch.com › t › 751548 › java › Execute-Linux-Command-Return-Output
Execute Linux Command and Return Output (Java in General forum at Coderanch)
May 9, 2022 - Java's Process can only execute one single command. Ron's solution works because it removes two of the commands. Tim Cooke's suggestion also would have worked - use a script. Because that would be a single command again to Process. SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Ron McLeod wrote:You should be able to just check the exit value from grep to determine if a match was found.