Domanda

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?

È stato utile?

Soluzione 2

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top