exec does not execute a command in your shell
try
CopyProcess p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
CopyProcess p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
Answer from KitsuneYMG on Stack OverflowBaeldung
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 - Quick guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX.
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.
Videos
03:11
Java - run system commands - 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
05:43
How to Run Java Programs With Command Prompt (cmd) and Notepad ...
Run Java in Command Prompt / Terminal | Compile and Run ...
Top answer 1 of 3
111
exec does not execute a command in your shell
try
CopyProcess p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
CopyProcess p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
2 of 3
35
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
Copyimport java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/narek/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/narek"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
GitHub
github.com › Dualcon › Java-ShellCommand
GitHub - Dualcon/Java-ShellCommand: Java - How to execute shell commands on Windows or Mac OS · GitHub
public static void main(String[] args) { String domainName = "google.com"; // Execute the command in windows String command = "ping -n 3 " + domainName; // Execute the command in Mac osX //String command = "ping -c 3 " + domainName; String output = executeCommand(command); System.out.println(output); } public static String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); }
Author Dualcon
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it's in. By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute commands directly or run .bat/.sh files.
Princeton CS
introcs.cs.princeton.edu › java › 15inout › linux-cmd.html
Java and the Linux Command Line
You will use the javac command to convert your Java program into a form more amenable for execution on a computer. From the shell, navigate to the directory containing your .java files, say ~wayne/introcs/hello, by typing the cd command below.
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - Your work will be more reproducible since using a shell your computer keeps a record of your every step. It enables people to re-do the work when needed and address others for checking or applying a process to new data. Runtime.exec() is a simple high-level class, not customizable at the moment but available in every Java application. It gives the possibility for the application to communicate within its environment. The exec() method is for executing commands directly or running .bat/.sh files.
Oracle
docs.oracle.com › en › java › javase › 11 › jshell › introduction-jshell.html
Java Shell User’s Guide
JShell was introduced in JDK 9. To start JShell, enter the jshell command on the command line. JDK 9 or higher must be installed on your system. If your path doesn’t include the bin directory, for example java-home/jdk-9/bin, then start the tool from within that directory.
GitHub
github.com › pollev › shell_command_executor_lib
GitHub - pollev/shell_command_executor_lib: A Java Lib designed to make executing shell commands easier and safer · GitHub
This is a Java library that intends to make it easier and safer to execute shell commands on the operating system using Runtime.exec().
Author pollev
Kevin Boone
kevinboone.me › exec.html
How to run a shell script from a Java application - Kevin Boone
Running a shell script from a Java program using Runtime.exec() appears simple. In practice, there are many pitfalls. This article describes how to avoid at least some of them.
Oracle
docs.oracle.com › javase › 10 › jshell › introduction-jshell.htm
1 Introduction to JShell
JShell is included in JDK 9. To start JShell, enter the jshell command on the command line. JDK 9 must be installed on your system. If your path doesn’t include java-home/jdk-9/bin, start the tool from within that directory.
Medium
medium.com › @bectorhimanshu › essential-shell-commands-every-java-developer-should-know-2e312f0c5720
Essential Shell Commands Every Java Developer Should Know | by bectorhimanshu | Medium
October 17, 2025 - Shell commands might feel intimidating at first, but start small — list files, check logs, move things around. Soon you’ll wonder how you ever worked without them. ... Navigate your filesystem and manage files. Read, search, and analyze logs. Control permissions and environment variables. Run and monitor your Java processes.
Medium
elvisciotti.medium.com › java-coin-the-command-line-with-shell-5-minutes-introduction-ab84f764f911
Java coin the command line with Shell. 5 minutes introduction
June 9, 2023 - Java shell prompt using JShell. 5 minutes intro TL; DR Type jshell and type auto-completed java code in a prompt, immediately executed. Use $1 to access output from previous commands, type /save …
Alexandru Nedelcu
alexn.org › blog › 2022 › 10 › 03 › execute-shell-commands-in-java-scala-kotlin
Execute Shell Commands in Java/Scala/Kotlin - Alexandru Nedelcu
October 5, 2022 - */ public static CommandResult executeShellCommand( ExecutorService es, String command, String... args ) throws IOException, InterruptedException { Objects.requireNonNull(command); Objects.requireNonNull(args); final String shellCommand = Arrays .stream(prepend(command, args)) .map(StringEscapeUtils::escapeXSI) .collect(Collectors.joining(" ")); return executeCommand( es, Path.of("/bin/sh"), "-c", shellCommand ); } private static String[] prepend(String elem, String[] array) { final var newArray = new String[array.length+1]; newArray[0] = elem; System.arraycopy(array, 0, newArray, 1, array.len
CodingTechRoom
codingtechroom.com › tutorial › java-run-shell-command-in-java
Run Shell Command In Java: A Comprehensive Guide - CodingTechRoom
This technique allows for the integration of Java applications with the underlying operating system for various tasks. ... Q. Can I run commands on Windows and Linux using the same code? A. Yes, by specifying the correct shell in the ProcessBuilder (e.g., 'cmd.exe' for Windows or 'bash' for Linux), you can write cross-platform compatible commands.