1

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.

1

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

4 Comments

Can you execute something like: "/usr/bin/sh cd /home/" perhaps?
But the problem is that I cannot source a shell script from java. Like on unix we source the shell script as /bin/ksh>. ./script But you cannot source the script like this from java I suppose.
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.
That's what !! So you cannot set an environment variable permanently from java. It will only be done in a subprocess and exit. Correct?
2

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.