trying to capture javac output in bash shell
Asked Answered
P

3

12

I'm trying to redirect the java compiler output to a file. I thought it's supposed to be:

javac file.java > log.txt

or something. Instead, I see all the output on the terminal and nothing in log.txt!

Also, if I want to log errors too, do I do

javac file.java 2>&1 > log.txt

?

Patriciapatrician answered 25/11, 2008 at 15:35 Comment(0)
G
15
javac file.java 2> log.txt

The reason is that you have two output file descriptors instead of one. The usual one is stdout, which you can redirect with > and it's supposed to be used for resulting output. The second one, stderr, is meant for human readable output like warnings, errors, current status etc., this one is redirected with 2>.

Your second line, using 2>&1, redirects stderr to stdout and finally stdout into log.txt.

Greenaway answered 25/11, 2008 at 15:41 Comment(4)
I see redirecting stderr gives me the output that I want. Why is everything logged in stderr and nothing in stdout? Also, could you tell me why javac file.java 2>&1 > log.txt doesn't work?Patriciapatrician
The redirections are handled left-to-right. The 2>&1 sends stderr to the place where stdout is currently going - the terminal. Then the >log.txt sends stdout to log.txt, leaving stderr writing to the original stdout. If you wrote >log.txt 2>&1, then all output would go to the file.Whitehouse
You get bonus points if you knew that this works too: >log.txt javac 2>&1 file.javaWhitehouse
The "philosophy" of stdout vs. stderr is that "cmd >foo.txt" should write something to the terminal if something goes wrong. javac follows this rule because all of its output is "something going wrong".Haynie
C
8

Have you tried

javac -Xstdout log.txt file.java

This will send compiler errors to a log file instead of stderr.

Calton answered 25/11, 2008 at 15:42 Comment(0)
M
0
javac -verbose file.java &> log.txt
Macneil answered 8/1 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.