7

I want to open the terminal (command prompt) on a Linux machine using Java code. I know how to open command prompt in windows.The following code i have used in windows

String command= "cmd c/start cmd.exe"
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);

I need the same thing in Linux.

Thanks for your answers. I would like to run a sh script also.

Whether the following code works.

String command= "usr/bin/xterm myshell.sh";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
alainlompo
  • 4,414
  • 4
  • 32
  • 41
user48094
  • 10,481
  • 12
  • 36
  • 30
  • Can you clarify? Do you want to open a terminal, or do you want to run a script? Users have a variety of different terminals, and you'd be hard pressed to guarantee that you can open one. But running a script, almost every linux box has /bin/sh (just not necessarily at that absolute path) – num1 Dec 29 '10 at 05:36

8 Answers8

8

In Linux, there are a number of terminal emulators which allow you to interact with various shells. Each shell is basically a command interpreter that understands Linux commands (GNU & Unix commands is more correct I suppose...). A terminal emulator provides an interface (window) for the shell and some other facilities for using the command prompt. To open a terminal window, you just have to modify your command string like this:-

import java.io.*;

class TerminalLauncher
{
    public static void main(String args[]) throws IOException
    {
        String command= "/usr/bin/xterm"; 
        Runtime rt = Runtime.getRuntime();  
        Process pr = rt.exec(command);
    }
}

The basic assumption I have made is that you want to open xterm, which is available on almost any system (with X installed of course). You might want to open another terminal emulator like rxvt, eterm, aterm, gnome-terminal or konsole. The command string can also be modified to use different shells like zsh. I suggest you catch an exception in case the terminal you chose isn't present and handle it by asking the user to install it. A better solution is to accept command line arguments for the users preferred shell or to use a configuration file which the user can change to make your script open the shell of his/her choice.

Note
1. As others have already pointed out, xterm (or any other terminal of your choice) may not be in the path specified (/usr/bin/...) and may not even be installed, so you might have to use some fancy command string (Ex: pipelining find through grep to get the path to xterm before launching), which isn't such a great idea. I think the best way is to let the user configure the whole thing.

2.I got a comment on this answer (by ypnos), suggesting that I avoid using absolute paths and rather rely on the command being in the PATH environment variable. I have to say I agree. In that case, the command string should be -

String command = "xterm"

Do look at the comment, because it also points out the problem with using find.

batbrat
  • 5,155
  • 3
  • 32
  • 38
  • 2
    Do _not_ use absolute paths on Linux for binaries. The command observes the PATH variable. If you just call it on "xterm", xterm will be found, if it is present in the system. – ypnos Feb 28 '09 at 18:55
  • 1
    p.s.: find is a terrible idea. locate would be slightly better. whereis is correct. BUT: to call find/locate/whereis, you would have to know their absolute paths as well ;-)) .... just don't use absolute paths it would drive you insane :D – ypnos Feb 28 '09 at 18:58
  • @ypnos I just saw your comment. Thanks for the tip. Being a beginner, I really appreciate the tip. I'll keep it in mind. – batbrat Mar 01 '09 at 06:59
  • I tried some operations on pr, its giving me null pointer exception. – Ruturaj May 28 '14 at 02:50
  • @ypnos Any program that wants to execute a specific tool on some Unix system should *definitely not* rely on user's PATH being set to a value that's guaranteed to get what you think it gets. Users are free to do with their PATH what they think is best, and can override anything with a shell script in their ~/bin. – laune Jul 02 '14 at 09:53
  • @batbrat See my previous comment. – laune Jul 02 '14 at 09:55
  • @laune That is exactly what PATH is for. So that you can mangle with it. If the user wants to replace xterm by another one in a custom path, she most likely also wants your program to use that version. If she finds that it doesn't work as expected, she can run the program with a different PATH. However, many users cannot change /usr/bin, or do not want to do so even if they have root access. So in almost all cases, adhering to the user's PATH variable is the expected behavior. Only in specific corner cases you might want to rely on the absolute path. – ypnos Jul 02 '14 at 11:35
  • @ypnos I don't know whether providing make files (where relying on PATH has the same destabilizing effect) in a SW development environment for 50+ SW engineers is what you consider a "corner case". Anyway, a (by stern requirements) traceable, reproducible and reliable build process is not possible without bypassing user settings such as PATH, aliases and environment. – laune Jul 02 '14 at 12:11
  • @laune What's the deal with make files? Do you want to give an example or where does this come from? – ypnos Jul 02 '14 at 13:27
  • @ypnos In addition to compilers and similar, make may contain many shell command sequences where various standard Unix tools are invoked that also have an impact on the produced artifacts (not only binaries). There are standards, applicable to the production of SW with a SIL > 0 that require you to record *exactly* how these artifacts have been built. I've been responsible for such a build environment for about 10 years, and you can take it for granted that bypassing user settings is essential. - Of course, that's very far from calling up an xterm without any depend.ability. – laune Jul 02 '14 at 13:56
  • @laune **what** **are** **you** **talking** **about**? The question has nothing to do with building. It is about how to open a terminal from a Java application. – ypnos Jul 02 '14 at 22:16
  • @ypnos I am merely objecting to your unconditional statement "Do not use absolute paths on Linux for binaries." There is no constraint in this sentence. – laune Jul 03 '14 at 04:34
4

There's no single standard "terminal" command on Linux - the ones available depend on which GUI is present (i.e. whether KDE, or Gnome, etc).

You should be able to rely on xterm being present, but on modern Linux variants that's not the terminal of choice:

String command= "/usr/bin/xterm";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);

Of course, "xterm" might not be in that particular path...

Alnitak
  • 334,560
  • 70
  • 407
  • 495
3

xterm will most probably be available on most Linux-based operating systems and if present will be found in the path variable.

Therefore, you will need to do something like this:

try {
    Runtime r = Runtime.getRuntime();
    String myScript = .....
    String[] cmdArray = {"xterm", "-e", myScript + " ; le_exec"};
    r.exec(cmdArray).waitFor();
} catch (InterruptedException ex){
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
}

The -e option can be used to invoke either a script or another program, for example: javac. In this case you would make an assignment like: myScript = "javac".

You will need the " ; le_exec" part if you do not want the window to immediately close after execution, otherwise discard it. The semi-colon is used to separate commands and le_exec is just a simple script that waits for the user to press Enter.

However, if your script needs arguments, then you would need to replace the String myScript by and array of Strings.

3

Under Gnome, it's gnome-terminal.

Under KDE, it's konsole.

Or you could use the more generic terminal program xterm.

You'll probably want to use options with most of this, so look up the man pages for the one you want.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

There isn't actually a "the" terminal. What you really want is shell. Most Linuxes uses BaSH as a shell, but to keep on the safe side you should restrict yourself to /bin/sh

Edit: Hmm I probably missunderstood the question. If you want an interactive terminal you should look into using a toolkit providing a component for that.

Edit2: Maybe your needs can be served by VTE which is a GTK+ component for embedding a terminal.

John Nilsson
  • 17,001
  • 8
  • 32
  • 42
1

I think it would be nice if your application will open user's default terminal application.

Unfortunately, it seems that there is no universal way to determine it.

In my opinion the most preferrable solution would be (stop whenever you can open something):

  • try to recongnize user's desktop environment and determine it's default terminal application. You can read something about it here.
  • check environment variable $TERM
  • Ask user for her preference and save it in configuration file.

Finding out user's desktop environment and it's default terminal might be too complicated for your purpose, so I'd use two last options. You can run application from $TERM with code like this:

String command = System.getenv().get("TERM");
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
begray
  • 15,911
  • 4
  • 22
  • 14
  • I didn't think of using $TERM. In any case, I know that it isn't always accurate. Both gnome-terminal and konsole set it to xterm (according to your link). – batbrat Feb 28 '09 at 13:09
  • That's right TERM is not meant to hold the name of the binary, but rather a name that can be looked up in /etc/termcap. gnome-terminal & xfce-terminal both use "xterm". When running a screen-session it's "screen". – Joachim Sauer Feb 28 '09 at 13:22
  • Also, if somebody starts a Java app from Desktop, TERM could likely be the real virtual console from which X and the whole session was started.. – ypnos Feb 28 '09 at 18:49
0

I would definitely provide an easy way to configure the path to the desired terminal in a place that can be easily edited. For example maybe in a configuration XML file.

Different distros will keep this in different places, so it's probably best to check the per distribution documentation for the platforms you're targeting (and to document how to change it).

"/usr/bin/xterm" should be on most machines, but I wouldn't necessarily bet the farm on it.

overstood
  • 985
  • 6
  • 7
0

since you have to assume you know almost nothing about the system you are running this on, I'd say lowest common denominator would be:

String command= "/bin/sh";

  • or even more 'guaranteed' -

String command= "sh";

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
  • That won't start a terminal emulator, only a shell. You should also use '/bin/sh' instead of '/usr/bin/sh' as the first is a POSIX requirement (i.e. guaranteed to be there for every Unix system). – Kristof Provost Mar 01 '09 at 11:29
  • The OP said: I want to open the terminal (command prompt), so they don't want a terminal emulator - but I agree about the /usr/bin/sh (and so have editted) – KevinDTimm Mar 01 '09 at 15:09