1

I am trying to create a linux shell script that compiles a program in java and runs it only if there are no errors from the compiler. This is my attempt, which doesn't work, and runs the program every time even if there are errors:

#!/bin/bash
cd ~/Desktop/Foo/src
compilerOutput=$(javac Foo.java)
if ["$compilerOutput" = ""]; then
    java Foo
fi

2 Answers 2

2

Like any decent Unix tool, javac should set its exit code to non-zero if there is an error.

javac Foo.java && java Foo

Behind the scenes, the shell examines the exit code (which is available as $? if you want to examine it explicitly) and takes the next action only if it is zero.

If you want more complex logic, you can say

if javac Foo.java; then
    date +"%c success" >>logfile.log
    java Foo
else
    date +"%c fail (exit code $?)" >>logfile.log
    echo "Oh dear" | wall
fi
Sign up to request clarification or add additional context in comments.

Comments

0

The root cause of problem is

compilerOutput=$(javac Foo.java)

When you use command substitution, only the standard output get assigned to compilerOutput

For javac there is no standard output, that is the standard output is always empty, What you see on the screen in standard error

There for even when there is no errors in the program or not

if ["$compilerOutput" = ""]; then

will always be true as the standard output is always empty


Solution

The proper way of doing this is to get the exit status of the previous command through the shell variable $?

Code

#!/bin/bash
cd ~/Desktop/Foo/src
javac Foo.java  2> errors
if [ $? = "0" ]; then
    java Foo
fi

Changes made

  • javac Foo.java 2> errors

    This statement redirects bstandard error to errors file

  • if [ $? = "0" ]; then

    Checks if the exit status of previous command, javac Foo.java is 0 (Successfull compilation)

5 Comments

Huh? This has syntax errors and logic errors both.
You need spaces in the brackets. Explicitly examining $? is an anti-pattern. Ditching the output and error messages is bad advice.
@tripleee Ok. I have corrected that and redirected errors to some file. But sorry i didnt get the Explicitly examining $? is an anti-pattern. part. Thank you.
if command; then is more idiomatic and shorter than command; if [ $? = 0 ]; then; there really is no reason to use the latter, ever.
@tripleee Will remember that !! Thanks a lot :) Since you have already added such an answer, I dont think there is any point in changing mine now. Will leave it like this

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.