0

I have the following program where I want to print a variable $var that I fill with the execution time of a program. However, when outputting it to the console with echo or printf the value is empty.

Program:

#!/bin/bash
for n in 1 2 3 4;
    do my_time="$(time var=$(echo "scale=100; 4*a(1)" | bc -l))";
    
    echo $var
    echo $my_time       
    printf "Value of PI is :%s\n" $var
done

Output:

real    0m0.003s
user    0m0.000s
sys 0m0.000s


Value of PI is :

real    0m0.004s
user    0m0.000s
sys 0m0.000s


Value of PI is :

real    0m0.004s
user    0m0.000s
sys 0m0.000s


Value of PI is :

real    0m0.004s
user    0m0.000s
sys 0m0.000s


Value of PI is :

Where is the problem, and how to solve it?

1 Answer 1

2

Command substitution $(...) runs the commands in a subshell. Setting a variable in a subshell isn't propagated to the parent shell.

In this case, it's even more problematic, as the time builtin doesn't output to the standard output or error. In order to be able to capture its output, you need to run it in a subshell and capture that shell's stderr - but that way, you can't set any variable.

The only possible way I see is to run the command twice, once capturing the output and once capturing the time:

    var=$(bc -l <<< 'scale=100; 4*a(1)')
    my_time=$( (time bc -l <<< 'scale=100; 4*a(1)') 2>&1 >/dev/null)

Or, capture both the details at the same time and separate them later:

    out=$( (time bc -l <<< 'scale=100; 4*a(1)') 2>&1)
    var=${out%real*}
    my_time=real${out#*real}
11
  • Hi Choroba, Thanks for your quick response. I changed the code but now it gives me error: CODE: do var=$(echo "scale=100; 4*a(1)" | bc -l) my_time=time($var) echo $var echo $my_time printf "Value of PI is :%s\n" $var OUTPUT: pi2.sh: line 5: syntax error near unexpected token `('
    – TKr
    Sep 4, 2021 at 20:28
  • What error? Also, check the update.
    – choroba
    Sep 4, 2021 at 20:31
  • Edited my previous comment but I just saw your edited answer. Will try that code, thanks a tom
    – TKr
    Sep 4, 2021 at 20:31
  • That's not what I posted.
    – choroba
    Sep 4, 2021 at 20:37
  • I run it using bash/ sh commands or using ./
    – TKr
    Sep 4, 2021 at 20:37

You must log in to answer this question.

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