1

I am attempting to read user input of strings that represent shell commands and execute those commands from Java. I have already seen that "cd" does not work (Exception in thread "main" java.io.IOException: Cannot run program "cd":) but this can be worked around. Similar for "export". I see now "echo" of an environment variable, set by providing arguments to exec, also does not work and I can't understand why "echo" would fail.

I would like to know in particular why "echo" does not work and in general what other commands will fail. If there is a broad category of such commands or if there are relatively few so that each can be worked around.

EDIT: I have a web UI and a textarea into which the user can enter multiple strings, each terminated by a newline. The program reads each string and then would like to execute each as a shell command or program, just as if the user had entered those commands at the command prompt. This seems to work for some user input using Runtime.exec but fails for other input.

EDIT: The other question which has an answer that answers my question seems to handle a single command, not a series of commands, one of which might affect subsequent commands. How does one handle a sequence of multiple commands?

releseabe
  • 323
  • 3
  • 13
  • You're trying to execute shell commands (`cd`, `export`) instead of programs. That's now what `Runtime.exec` is for. `echo` actually is also a separate program and should work (try `which echo` in a terminal), but it won't do shell variable expansion, because `Runtime.exec` is not a shell. – vanza Nov 18 '20 at 22:45
  • @vanza: is there anything that will execute shell commands or programs? if a human was sitting at a terminal, each "thing" he typed would run -- why can't a Java program do the same thing? – releseabe Nov 18 '20 at 22:48
  • The terminal is running a shell (e.g. `/bin/sh`). You can also run the shell with `Runtime.exec`. But then you're getting into what you're trying to do here. You question is a bit too vague to help with that. – vanza Nov 18 '20 at 22:52
  • @vanza let me try to clarify the question. – releseabe Nov 18 '20 at 22:56

0 Answers0