Ritwik Bose
Ritwik Bose

Reputation: 6069

Running Shell scripts through java

So I have a java class that takes individual commands and puts them into the shell through the Runtime and Process objects. My problem is that I can run a command like:

$ls /users/me/documents

and it will work, but

$cd /users/me/documents
$ls

still lists the root. Obviously the Process and runtime objects don't keep track of where it is. Is there any way to capture the terminal object, or do I have to keep track of the current directory manually?

Upvotes: 0

Views: 418

Answers (3)

duffymo
duffymo

Reputation: 308733

Everyone who uses Runtime.exec needs to read this.

Upvotes: 2

jqa
jqa

Reputation: 1370

You are spawning a separate process for each command. Put the commands into a script and execute it in one process

Upvotes: 2

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

Each shell script is going to start fresh. You will need to string all your command together:

cd /usr/me/documents && ls

cd /usr/me/documents; ls

The first variation will only run ls if the cd was successful (so if the directory was bad, ls will not run). The second variation will always run ls (so if the directory was bad, ls will run in the default directory).

Upvotes: 2

Related Questions