Thursday, May 9, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 1783  / 3 Years ago, sat, june 12, 2021, 2:01:55

This will sound pretty awkward for some of you. Suppose I have a string which represents some $((expression)), arithmetic expression mathematical like '$((1+1))'. I wish to perform it and deliver its result to a variable.


Example:


$ expression='$((5+5))'
$ echo $expression
'$((5+5))'

$ # Expected result: 10

How can I evaluate that string and store its result?


More From » command-line

 Answers
2

If you're evaluating a string try eval.


str="$[ 5 + 5 ]"
eval "numb=$str" # Turns into `numb=$[ 5 + 5 ]`
echo $numb # Outputs 10

eval can execute strings as if they were shell code. Be careful! If $str can contain special characters it may break your script or even create a security hole.


[#809] Saturday, June 12, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skipu

Total Points: 366
Total Questions: 114
Total Answers: 112

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
skipu questions
Sun, Dec 26, 21, 05:25, 2 Years ago
Wed, Oct 6, 21, 10:26, 3 Years ago
Sun, Oct 31, 21, 02:01, 3 Years ago
Tue, Feb 14, 23, 19:48, 1 Year ago
Tue, Feb 22, 22, 08:37, 2 Years ago
;