2

I am currently trying to make a bash script that will go into every folder in ./ and compile blah.java, then run blah sending in a number for an input, and put the output in a file that I have named. I have something that is somewhat functional, but it only goes into the first directory, and after that it fails on me. I currently have...

#! /bin/bash


for i in $(find . -maxdepth 1 -type d)
do

    pwd
    cd $i
    pwd

    if [ -f "blah.java" ];
    then
        javac -cp . blah.java
        echo "17" | java -cp . blah - > blahresult17
        echo "43" | java -cp . blah - > blahresult43

    fi

done

I think it is having problems, because it is trying to go into a directory from ./ once it goes into a subdirectory, but obviously from the subdirectory it doesn't exist.

1
  • 1
    it seems like you could use javac task of ant rather than writing a script Commented Oct 16, 2012 at 14:33

3 Answers 3

1

You're missing a fi on your if, but that's presumably a cut and paste error, not the source of your failure. The likely problem is that once you do the first cd, the following cd commands are relative to where you were, not where you are now. You can work around this with pushd/popd instead, or running the cd and java bits in a subshell so that the cd does not persist to the next loop iteration.

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

1 Comment

Yes that was a cut/paste error. You were correct that it didn't go back up a directory
1

You cd into the directory but never cd out of it.

My suggestion: use pushd/popd instead of cd.

Replace cd $i with pushd "$i" and put popdat the end of your loop.

Also for dir in */ would be a simpler solution to iterating all directories in the current directory.

Comments

0

This is another way, if you wanted to compile all the files with one invocation of javac, which allows javac to handle dependencies:

SRC=`find src -name "*.java"`
if [ ! -z $SRC ]; then
    javac -classpath $CLASSPATH -d obj $SRC
    # stop if compilation fails
    if [ $? != 0 ]; then exit; fi
fi

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.