Save terminal output to a txt file

For the delivery I've been advised to print the full output of my program to a txt file. Also I need to print the execution time using the command "time" that I have implemented in my execution script.

#!/bin/bash
time ./blur-effect 4k.png 4k_out16.png 16 15 &>> Output.txt 

The problem I'm having is that the program output is going correctly to the txt file, but the execution time is being showed in the terminal but it must be printed also in the txt file.


Solution 1:

It should work the way you want if you wrap the command in a command group or subshell:

{ time ./blur-effect 4k.png 4k_out16.png 16 15 ; } &>> Output.txt 

or

(time ./blur-effect 4k.png 4k_out16.png 16 15) &>> Output.txt 

See Write output of time in a file, why are parentheses needed?

Solution 2:

In Bash, time is a shell key word for pipelines which interprets stream redirection to occur only on the timed command (pipeline); it also happens to be a common *nix utility program:

$ type -a time
time is a shell keyword
time is /usr/bin/time

If you want to redirect streams to/from time you can either use command groups or sub-shells as explained in steeldriver’s answer or call the time(1) utility program explicitly:

/usr/bin/time COMMAND... &> LOGFILE

or if you’re unsure about the full path of time

time="$(which time)"
"$time" COMMAND... &> LOGFILE

P.S.: You can save the output of the time(1) command to a file that is not connected to the command’s standard error output (which is the default) in case you want to preserve the timed program’s standard error output unaltered with the -o option. -a makes time append to that file instead of overwriting it.

/usr/bin/time [-a] -o time.log COMMAND... >command-stdout.log 2>command-stderr.log

To achieve the same effect with the time shell key word (as usual, use >> instead of > redirection to append instead of overwrite):

{ time COMMAND... >command-stdout.log 2>command-stderr.log; } 2>time.log

Or to save the time log but leave the timed program’s standard error output as it is:

{ time COMMAND... 2>&3; } 3>&2 2>time.log