0

I am using a bash to compile c++ and Java programs. I need to use the data that time adds, "real", "User", "Sys". Even though I used var=$( compile ) to get output it shows nothing.

Is there a way to get as a varialbe the outout data of time?

Edited:

I am running the bash on Java with a Proccess and reading the InputStream with a BufferReader.

Jorge Monroy
  • 408
  • 1
  • 5
  • 16
  • 1
    Cross-site dupe: https://serverfault.com/questions/175376/redirect-output-of-time-command-in-unix-into-a-variable-in-bash – Benjamin W. Aug 07 '18 at 19:26
  • 1
    And closely related (asks about redirection to file, but underlying problem is the same): https://stackoverflow.com/questions/13356628/how-to-redirect-the-output-of-the-time-command-to-a-file-in-linux – Benjamin W. Aug 07 '18 at 19:27
  • and [BashFAQ/032](http://mywiki.wooledge.org/BashFAQ/032) – Benjamin W. Aug 07 '18 at 19:28

2 Answers2

1

You can get the full output time echo "hi", and save this to a variable:

stats=$({ time echo "hi"; } 2>&1)

or to a file:

{ time echo "hi"; } >mylogfile.txt 2>&1

The brace syntax here lets bash know what actual information you want. Because time is a reserved word in bash (like if or while), as well as a built-in, redirecting stdout or stderr without braces will not redirect the output from time. To do that, we need to group all the output from the command together, and then redirect it.

However, if you only want the timing info, we can redirect the command's information to the void /dev/null and keep only time's output. We can save this to a variable:

stats=$({ time echo "hi" 1>/dev/null 2>&1; } 2>&1)

or to a file:

{ time echo "hi" 1>/dev/null 2>&1; } 2>mylogfile.txt
jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
  • `time` is, at least in Bash, more likely a built-in, so `man time` isn't authoritative, as it refers the binary at `/usr/bin/time` or wherever it is installed; `help time` or the Bash man page would have to be consulted. – Benjamin W. Aug 07 '18 at 19:58
  • (Which has on effect on the solution of redirecting stderr.) – Benjamin W. Aug 07 '18 at 19:59
  • `help time` is super unhelpful imo. `man time` at least points out that the output is in stderr, even if it shouldn't be taken as gospel. – jeremysprofile Aug 07 '18 at 20:01
  • Helpful or not, `man time` talks about something most likely not being executed when you do `time `. It's not shipped with Bash. `man bash` has more information under SHELL GRAMMAR / Pipelines, but still doesn't mention that output goes to stderr. It could be argued that writing to stderr is simply [POSIX conformant](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html) and also intuitively makes sense, as otherwise the output from `time` would pollute a pipeline that's being measured. – Benjamin W. Aug 07 '18 at 20:10
1

Time output goes to the error output, so you can use getErrorStream in the process, and then you will get the output from time.

grisaf
  • 76
  • 3