Question

Might be a simple problem, but I am running CentOS 5.4 command line remotely. I want to redirect the output of a simple Java file, lets say loop to print a hundred thousand numbers in console to a text file. The thing is, I have to use the 'screen' command to be able to run it in background even if I loose my session with the remote computer and this command does not write to the desired file.

I tried the method screen java MyClass >& log.txt also screen java MyClass > log.txt but it does not write to the file. Why is this happening and is there any solution?

Was it helpful?

Solution

You can do this with the nohup command. Here's an example.

$ cat Foo.java 
public class Foo {
    public static void main(String[] args) throws InterruptedException
    {
        for(int i = 0 ; i < 1000 ; i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}

$ javac Foo.java
$ nohup java Foo > foo.txt &
[3] 29542
$ cat foo.txt 
0
1
2
3
4
5
$ exit

<< relaunch shell >>

$ cat foo.txt 
0
1
...
29
30

The reason this doesn't work with screen is because screen doesn't interpret your arguments like the shell does. If you were to do this with screen, it would have worked:

screen /bin/bash -c 'java Foo > foo.txt'

OTHER TIPS

sample_script.sh

#!/bin/bash
#start screen in detached mode with session name 'default_session' 
screen -dmS "default_session"
#redirect output to abc.log 
screen -S default_session -X stuff "script -f /tmp/abc.log\n"
#execute your command
screen -S default_session -X stuff "your command goes here...\n"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top