tags:

views:

2359

answers:

4

Why can't internal unix commands (cd, pwd, etc) be run directly in java like external commands (chmod, chown, etc) using Runtime.getRuntime().exec() ?

Please help with explanation.

+2  A: 

Java needs an executable file to, well, execute. That's why shell built-in commands (such as cd, bg, alias) do not work from Java. Built-in commands are not actual executable files, but are simply interpreted by the shell when the shell encounters them on the command line or in a script.

You might be able to get around this by writing a shell script containing the built-in command and then executing the shell script from the Java application.

Jeff
Can you execute something like: "/usr/bin/sh cd /home/" perhaps?
OscarRyz
But the problem is that I cannot source a shell script from java. Like on unix we source the shell script as /bin/ksh>. ./scriptBut you cannot source the script like this from java I suppose.
Vicky
You can run `/bin/sh -c cd /home/`, but it doesn't do anything. It just changes the pwd of the shell process which then immediately exits.
Tom Hawtin - tackline
That's what !! So you cannot set an environment variable permanently from java. It will only be done in a subprocess and exit. Correct?
Vicky
+6  A: 

Because they are built into the shell, rather than being programs in and of themselves.

The simplest thing to do is to invoke the shell and pass the command in using the -c option:

> bash -c pwd
/home/foo/bar/baz

... or in Java:

Runtime.getRuntime().exec("bash -c pwd")

... or more generally:

Runtime.getRuntime().exec(new String[]{"bash", "-c", command});

We need to use the String[] variant, otherwise, our command will get mangled by the StringTokenizer if it contains any whitespace.

Aaron Maenpaa
+2  A: 

You might want to read "When Runtime.exec() Won't".

duffymo
+1  A: 

Others have provided the basic reason, but they haven't really explained why this should be so.

The shell commands cd and pwd are internal to the shell because they affect or report on the internal state of the shell.

Both of the examples here work on the "working directory", which is part of the internal state of the shell, though the environment variable PWD is kept up to date with thin information as well.

To achieve the same effect in your program, you need to change or access the internal state of your process. Getting and setting the state of the environment variable PWD would be a reasonable, if unixish way to accomplish this.

dmckee