2

I want to time reading bash history and put the result into a variable. Unfortunately, time (which is a shell keyword) prints the result to stderr, and apparently redirecting stderr from shell keywords doesn't work the same as redirecting regular command output. In other words,

foo=$(time history -r 2>&1)

doesn't work (foo variable is empty, output is printed to terminal). How can I capture the output of time keyword?

Note: since history is a shell builtin, I cannot use external time command (i.e. /usr/bin/time) - I have to use time keyword in bash.

Jan Warchoł
  • 3,091

1 Answers1

4

You can use the following syntax:

foo=$((time history -r) 2>&1)

Placing the command in a () and redirect its stderr to stdout


Example:

$ foo=$((time history -r) 2>&1)
$ echo $foo
real 0m0.001s user 0m0.000s sys 0m0.000s
$ 
Yaron
  • 4,289