hewhocodes
hewhocodes

Reputation: 3

Bash multiple integers one variable

I'm trying to figure out how to add multiple integers that are on a variable separated by whitespace.

ex.

num1=10 20 30

should output 60

but I get an error when trying to echo the variable.

Upvotes: 0

Views: 987

Answers (3)

Léa Gris
Léa Gris

Reputation: 19675

Alternatively with a POSIX shell without string substitution:

num1='10 20 30'

# Transfer space Field Separated num1 into arguments array
IFS=' ' set -- $num1

# Join back arguments into num1 using + as Field Separator and compute
IFS='+' num1="$((10#$*))" # 10# sets base 10 to prevent handling leading 0 as octal numbers.

# Print 60
echo "$num1"

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50815

Substitute spaces with plus sign within arithmetic expansion.

$ num1='10 20 30'
$ echo $((${num1// /+}))
60

Upvotes: 1

Cyrus
Cyrus

Reputation: 88999

With bash:

declare -i num1   # set integer attribute
num1=10+20+30
echo "$num1"

or

num1=$((10+20+30))
echo "$num1"

Output:

60

Upvotes: 1

Related Questions