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.

1

1 Answer 1

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
$ 
1
  • 1
    or with just { time history -r; } instead of ( ), it doesn't need a subshell in particular
    – ilkkachu
    Commented Mar 11, 2018 at 11:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .