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
🌐
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....
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);
    }
}
🌐
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.
🌐
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.
🌐
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(); } } }
Find elsewhere
🌐
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.
🌐
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....
🌐
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().
🌐
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.
🌐
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.
🌐
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.
🌐
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).
🌐
DZone
dzone.com › coding › languages › execute shell command from java
Execute Shell Command From Java
August 14, 2008 - Join For Free · String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line=buf.re...
🌐
Alvin Alexander
alvinalexander.com › java › java-exec-system-command-pipeline-pipe
Java exec: How to execute a system command pipeline in Java | alvinalexander.com
Jumping right in, let's imagine that you want to run the following Unix/Linux command from your Java application: ... package com.devdaily.system; import java.io.IOException; import java.util.*; public class ProcessBuilderExample { public static void main(String[] args) throws IOException, InterruptedException { // you need a shell to execute a command pipeline List<String> commands = new ArrayList<String>(); commands.add("/bin/sh"); commands.add("-c"); commands.add("ls -l /var/tmp | grep foo"); SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands); int result = commandExecutor.executeCommand(); StringBuilder stdout = commandExecutor.getStandardOutputFromCommand(); StringBuilder stderr = commandExecutor.getStandardErrorFromCommand(); System.out.println("STDOUT"); System.out.println(stdout); System.out.println("STDERR"); System.out.println(stderr); } }
🌐
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.
🌐
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