Dan Dan - 2 years ago 80
Bash Question

Running commands in shell scripting

I have a very simple shell script which is meant to compile and run a


javac SomeJavaFile.java
java SomeJavaFile

However this script seems to stop before it fires the
commands. In essence the script may as well look like this


How would I be able to fix this problem?


As per suggestions and answers my script now looks like this

x-terminal-emulator -e "javac DropboxStatusLoop.java && java DropboxStatusLoop"

However it opens then closes instantly. I think this is strange since there is a loop going in my code.

Very simplistically, my code looks like this

import java.lang.*;

public class SomeJavaFile {
public static void main(String[] args) {
for(long i = 0; ; i++) {
try {
} catch (Exception e) {

It does compile and run properly when done manually, however, it has the same problem with the terminal opening and closing which was mentioned before. I believe this is because of
which may make the terminal think it has finished what it is doing so it stops and closes. Any help in fixing this is appreciated.

Answer Source

The problem is that your script will run x-terminal-emulator which opens a new instance of a terminal, then it waits for that process to finish before continuing. There isn't anything that will make it finish though, it will just open and wait.

The Java compiling and running commands aren't passed to x-terminal-emulator, rather they are simply commands in your script that are executed after x-terminal-emulator finishes running.

To pass the Java commands to run in x-terminal-emulator, use the -e option like this:

x-terminal-emulator -e "javac SomeJavaFile.java && java SomeJavaFile"

This will send the commands to x-terminal-emulator.

But unless you very specifically want to open another shell when this program runs, you most likely don't want to use x-terminal-emulator. Simply remove that line from the script so it becomes:

javac SomeJavaFile.java
java SomeJavaFile

Also note that you probably don't want to run java SomeJavaFile if the compiling failed, so you could make it so it only runs when the compiling was successful:

javac SomeJavaFile.java && java SomeJavaFile

For all cases, if you want to double-click on the file icon to run it, you will need to make it executable.

chmod +x script.sh

Where script.sh is the name of your script file.

Edits for troubleshooting

Make a new file myScript.sh with this:

javac SomeJavaFile.java && java SomeJavaFile

Then run the chmod command on it:

chmod +x myScript.sh

Then double click its icon, or run it with ./myScript.sh.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download