1

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.

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.