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.
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.
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.
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.
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.