0

OK, this is what I'm trying to do :

  • Execute a command, and time it at the same time (using time)
  • Get its output
  • Get time elapsed

That's my code so far :

for filepath in $files
do
(
output=$(time $filepath &>1)
echo ${output}
)
done

However, every command still outputs its time to screen, and $output contains the command's output.

Any ideas how to get both of them?

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • possible duplicate of [Struggling to parse (bash) time command](http://stackoverflow.com/questions/3928430/struggling-to-parse-bash-time-command) – devnull Apr 30 '14 at 10:54

2 Answers2

2

time writes its output to stderr or to a <file>, if -o <file> option specified (supported by both GNU and FreeBSD time). So I think you can't avoid using a (temporary) file to achieve the goal. You may use mktemp command to safely create a temporary file in shell.

user3159253
  • 16,836
  • 3
  • 30
  • 56
  • 1
    Just to be clear, you're describing the `time` program, not `bash`'s built-in command. `command time $filepath > output.txt 2> time.txt`. – chepner Apr 30 '14 at 11:18
1

You have to catch stdin and stdout. For this, and based on the solution in Is there a way to redirect time output to file in Linux, I would say do:

{ time command ; } 2>&1
                   ^^^^
                   redirect stderr to stdin

So you for example do:

$ var=$({ time echo 1 ; } 2>&1 )

$ echo "$var"
1

real    0m0.000s
user    0m0.000s
sys     0m0.000s
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • I think he meant to get `time` results and program output separately. If no then this answer is more correct than mine – user3159253 Apr 30 '14 at 11:08