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 Overflow
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);
    }
}
🌐
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 - So, before we create any Process ... referred to as cmd.exe. Instead, on Linux and macOS, shell commands are run using /bin/sh....
🌐
Kevin Boone
kevinboone.me › exec.html
How to run a shell script from a Java application - Kevin Boone
The fundametal problem raised in the last few sections is that Runtime.exec() is not a command-line processor — it's only a process launcher. As well as not tokenizing very intelligently, it won't expand shell wildcards (*.txt), or substitute environment variables ($HOME). If you're launching a shell script, you should expect to have to do any of this kind of thing in the script itself. In practice, the shell might need to be told where to find the script something.sh. On Linux the shell won't necessarily look in the current directory, although it might look in the directories specified in $PATH.
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › linux-cmd.html
Java and the Linux Command Line
In case you don't know, type the following command: [wayne] ~> echo $SHELL Your shell will likely be bash, tcsh, sh, or ksh. To make sure Linux can find the Java compiler and interpreter, edit your shell login file according to the shell you are using.
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - c:mysql then the prompt changes to: mysql> now in this we type sql commands. Can we achieve/automate this with java? ... The article would be even better with a note on how to run a shell file sitting in the resources directory. Thanks for the jump start anyway ! ... I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands.
Top answer
1 of 1
15

I am not sure if you are asking about Shell command execution, or ipconfig in general.

If the first is the case here: Yep, you can use Runtime.getRuntime.exec(). Related Answers (In Stackoverflow):

  1. Executing shell commands from Java
  2. Want to invoke a linux shell command from Java

Moreover to the answers provided there, here is my example on how you do it with "host -t a" command for DNS lookups. I would generally recommend to read through the list you get and append them in an String for logging purposes.

p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();
     
BufferedReader reader = 
  new BufferedReader(new InputStreamReader(p.getInputStream()));
     
String line = "";           
while ((line = reader.readLine())!= null) {
    sb.append(line + "\n");
}

The other solution which herausuggested was to use ProcessBuilderand execute the command from there. For this you need to use Java SE 7 upwards. Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

 ProcessBuilder pb =
   new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 File log = new File("log");
 pb.redirectErrorStream(true);
 pb.redirectOutput(Redirect.appendTo(log));
 Process p = pb.start();
 assert pb.redirectInput() == Redirect.PIPE;
 assert pb.redirectOutput().file() == log;
 assert p.getInputStream().read() == -1;

If you wanna know more about ProcessBuilder, read through the documentation: Oracle Documentation on Class ProcessBuilder

🌐
Admfactory
admfactory.com › home › how to execute shell command from java
How to execute shell command from Java | ADMFactory
June 20, 2018 - Note: depending on your system configuration you might need permission to run a specific command. package com.admfactory.io; import java.io.BufferedReader; import java.io.InputStreamReader; public class ExecuteShellCommandExample { public static void main(String[] args) { System.out.println("Execute shell commands example"); System.out.println(); try { String cmd = "ping admfactory.com"; System.out.println("Executing command: " + cmd); Process p = Runtime.getRuntime().exec(cmd); int result = p.waitFor(); System.out.println("Process exit code: " + result); System.out.println(); System.out.println("Result:"); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } }
🌐
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 - When we use either the ProcessBuilder or the Runtime classes to run Native shell commands, we make the Java program dependent on the underlying operating system. For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands.
Find elsewhere
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-to-execute-native-shell-commands.html
How to Execute Native Shell commands from Java Program? Example
Suppose you want to execute the ... are two main approaches for executing shell commands in Java either by using Runtime.exec() method or ProcessBuilder, which was added in Java 1.5....
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
🌐
Javaprogramto
javaprogramto.com › 2019 › 04 › how-to-run-unixshell-command-in-java.html
How to run unix/shell command in java like chmod, mkdir, grep or any unix commands JavaProgramTo.com
April 30, 2019 - Runtime.getRuntime().exec("sh -c grep -i 'exception' /home/java_w3schools/java/server.log); Print all the lines which is having exception word ignoring case in server.log · This class is used to create operating system processes. command() method to add the commands to the process builder and need to invoke the start() method to start a new process on the underlying operating system.
🌐
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 - For one thing, there's only about 8 different shells available to Linux users, so you'd have to indicate which one to use. Put the commands into a shell script and exec() something like "/usr/bin/sh /absolute/path/to/my/script". Finally, to capture stdout/stderr or set stdin on Runtime.exec() is a lot messier, if I recall, than in that example. You basically have to pre-allocate Java Streams and feed them in as part of the exec().
🌐
Redpill Linpro
redpill-linpro.com › techblog › 2024 › 02 › 21 › java-21-shell-scripts.html
Portable Java shell scripts with Java 21 – /techblog
February 21, 2024 - The filename of the script itself ($0) is passed as the <sourcefile> argument to java and any additional arguments that were passed to the script ($@) are passed as command-line arguments to the Java program: ///usr/bin/env java --source 21 --enable-preview "$0" "$@" The Java launcher will both compile and run the program.
🌐
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - In this article, we will take a close look at the importance of shell command that minimizes the possibility of an error during your work and how to execute it within Java code. There are two possible ways: the first is the Runtime class and that’s the exec method, and the second is the ProcessBuilder instance.
🌐
Medium
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 are providing commands to execute. Notice, for Windows, we are running cmd(command prompt) and for Linux-based operating system sh(shell).
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-run-shell-command-in-java
Run Shell Command In Java: A Comprehensive Guide - CodingTechRoom
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. Q. What are some common shell commands I can run from Java?
🌐
GitHub
gist.github.com › sangupta › 9d432f8368811533f99fec44b3ea9428
A simple shell script to run a Java program from Linux shell in the background · GitHub
This is a simple script to run a Java program from Linux shell in the background - so that the process does not terminates when you log out of the shell.
Top answer
1 of 10
64

You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

When compiled and run, it outputs:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

2 of 10
27

You can also write a shell script file and invoke that file from the java code. as shown below

{
   Process proc = Runtime.getRuntime().exec("./your_script.sh");                        
   proc.waitFor();
}

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.