0

I'm having some trouble capturing the output of a command in Bash.

I have a Bash script to test a C program...

bufsize=1
while [ $bufsize -le 16384 ]
do
    runtime=$(/usr/bin/time -f "%e" -o /dev/tty \
    ./raw_copy $bufsize ./country_vaccinations.csv raw_copy.out)
    
    echo "Runtime for array with $bufsize slots was $runtime."
    
    bufsize=$(( $bufsize * 2 ))
done

(it tests how fast the program raw_copy, which we wrote, copies a file, based on how much memory the program is allowed to use. This is an assignment.)

I've tried a few different variants of capturing the output of the time command into the variable called runtime. E.g., runtime=$(stuff) as above, runtime="$(stuff)", and also varying the quotes in the echo command. However I can't quite get what I'm looking for. The output I keep getting is

$ ./test4.sh 
0.60
Runtime for array with 1 slots was .
0.30
Runtime for array with 2 slots was .
0.15
Runtime for array with 4 slots was .
0.07
Runtime for array with 8 slots was .
0.04
Runtime for array with 16 slots was .
0.01
Runtime for array with 32 slots was .
0.01
Runtime for array with 64 slots was .

(et cetera)

and as you may be able to tell I'm looking for something more like

$ ./test4.sh
Runtime for array with 1 slots was 0.60.
Runtime for array with 2 slots was 0.30.

(et cetera)

Just thought I'd see if someone could help me out. (So essentially I'm just having a hard time figuring out how to save the output of the time command into a variable, instead of just printing it.)

1 Answer 1

2

By default at least the time on my Debian outputs to stderr, which isn't good using it in a command substitution. Though in your command, you're telling it to print to /dev/tty, directly to the terminal, which also doesn't work.

Tell it to print to /dev/stdout instead:

t=$(/usr/bin/time -f "%e" -o /dev/stdout sleep 1)
echo "that took $t s"

or, with a redirection in the shell:

t=$(/usr/bin/time -f "%e" sleep 1 2>&1)
1
  • Awesome, that does just what I'm looking for. Apparently I need to learn a little about tty versus stdout. Thanks. Commented Feb 6, 2021 at 21:21

You must log in to answer this question.

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