Zach Nudelman
Zach Nudelman

Reputation: 13

Appending time to a file in unix

I have a program which I input a final into:

time java SearchIt < input.txt

I then wish to append the output of the time method into a new file SearchIt\ Results.csv

I know how to save it to a new file:

(time java SearchIt < input.txt)&>SearchIt\ Result.txt

However, this creates a new file each time I execute the code. I tried

(time java SearchIt < input.txt)&>>SearchIt\ Result.txt

But got a syntax error

-bash: syntax error near unexpected token `>'

Any help would be great, thanks!

Upvotes: 0

Views: 224

Answers (2)

Fred
Fred

Reputation: 6995

Try this :

(time java SearchIt < input.txt) >>SearchIt\ Result.txt 2>&1

This sets up a redirection that appends standard out to a file (the >> portion), and then it redirects standard error to the same place (2>&1).

Please note that the ordering is important for redirections, you need to have 2>&1 after the first redirection.

Please note that you could also use a code block instead of a subshell :

{ time java SearchIt < input.txt ; } >>SearchIt\ Result.txt 2>&1

And, really, you do not need any subshell or code block in this case, all redirections can coexist in a single command (in this simple case).

time java SearchIt < input.txt >>SearchIt\ Result.txt 2>&1

It you want to suppress the output of the application, but keep the output of the time command, then you can do this :

{ time  { java SearchIt < input.txt >/dev/null ; } ; } >>SearchIt\ Result.txt 2>&1

Please note this will discard the standard output of the java application, but keep its output to standard error (which is usually useful). Add 2>&1 after >/dev/null if you really want to get rid of all output.

The performance impact in your case is probably insignificant, but as a general rule, you should avoid subshells when possible as a matter of good coding practice. Aside from performance, there are benefits to that in variable scoping (not relevant here though). Code blocks are just syntax to tell the shell how to execute the commands, they do not create additional processes by themselves, and extra code blocks have negligible impact on performance.

By the way, &>> should work on Bash 4 and newer, so you probably are using an older version, or not using Bash.

Upvotes: 1

Paul Grinberg
Paul Grinberg

Reputation: 1427

To append STDOUT of your process to a file and time commands output (which is going to STDERR) to another file, then you can do

(time java SearchIt < input.txt) 1>> SearchItOutput.txt 2>> TimeOutput.txt

If you don't care to save your process' STDOUT but still print it, then you can simply do

(time java SearchIt < input.txt) 2>> TimeOutput.txt

If you want to not even print your process' STDOUT (assuming you are on a linux-like system)

(time java SearchIt < input.txt) 1> /dev/null 2>> TimeOutput.txt

Upvotes: 0

Related Questions