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?
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.
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.
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.
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.
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'
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With