How to Convert String to Integer in Bash (With Example)


Often you may want to convert a string to an integer in Bash to perform some arithmetic operation.

In Bash, it’s important to note that you don’t “convert” a variable from one data type to another.

Rather, variables are simply treated as strings or integers based on the task you’re attempting to perform.

To force a variable to be treated as an integer, you can use the $((. . .)) operator.

For example, if you want to calculate the sum of two variables named var1 and var2 then you can use the following syntax:

echo $(($var1+$var2))

The following example shows how to use this syntax in practice.

Example: How to Convert String to Integer in Bash

Suppose that we create two variables in Bash named var1 and var2 that both contain integer values.

Suppose we attempt to calculate the sum of these two variables by using a plus ( + ) sign as follows:

var1=5
var2=10
echo $var1+$var2

The following screenshot shows how to use this syntax in practice:

By default, Bash concatenates the two variables together into one string for a result of 5+10.

To explicitly tell Bash that we would like to treat the variables as integers, we can wrap them in the $(( . . .)) arithmetic expansion operator as follows:

var1=5
var2=10
echo $(($var1+$var2))

The following screenshot shows how to use this syntax in practice:

Bash convert string to integer

Notice that Bash now treats the variables as integers and calculates the sum of the two variables to get 5 + 10 = 15.

Also note that you can drop the $ symbols inside of the arithmetic expansion operator if you would like:

var1=5
var2=10
echo $((var1+var2))

The following screenshot shows how to use this syntax in practice:

Notice that this returns the same result of 15.

Note: In this example we simply added two variables together but you can perform much more complex arithmetic operations within the $((. . .)) if you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract First Number from a String
Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply