Masa Hu
Masa Hu

Reputation: 137

Why Can I add a String and a Int in Bash

a="5"
b=1
c=$((a+b)
echo $c

c prints out 6

a="banana"
b=1
c=$((a+b))
echo $c

c prints out 1

How does bash recognize a="5" as an integer? Why does a="banana" become 0?

Upvotes: 0

Views: 1396

Answers (1)

Fred
Fred

Reputation: 6995

Bash knows nothing about integers as a true data type for variables.

Arithmetic expressions parse strings to convert them to integers internally.

You can declare a variable as an integer, like this :

declare -i var

This will not really make the variable an integer, it will still be usable as any variable. It will, however, cause assignment attempts to be interpreted as arithmetic expressions (and uninitialized variables they contain as having value 0).

For instance :

a=1
b=2
declare -i var
var=a+b+3
echo $var # Prints 6

I cannot state this authoritatively, but I expect "integer" variables to simply be a shortcut to make any assignment behave as if it were enclosed in $(()).

Upvotes: 1

Related Questions