Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output redirection with "screen" command

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?

like image 284
javaCity Avatar asked Feb 27 '12 05:02

javaCity


People also ask

Which command will redirect who output?

The >> shell command is used to redirect the standard output of the command on the left and append (add) it to the end of the file on the right.

What command do you use to output data to the screen?

You can use the tee command to output text from a command both to the screen and to a file. The tee command takes data from standard input and writes it to standard output as well as to a file.

How do I redirect output to a file and screen in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.

What command redirect output to a file and displays the same contents on the screen?

The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files.


2 Answers

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'
like image 183
mpontillo Avatar answered Sep 20 '22 04:09

mpontillo


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"
like image 29
Nikhil Avatar answered Sep 21 '22 04:09

Nikhil