Bash Convert String to Number


Bash Convert String to Number

In Bash scripting, converting a string to a number is useful for various tasks that require performing arithmetic operations on string inputs.


Syntax

number=$((string))

The basic syntax involves using arithmetic expansion $(( )) to convert a string to a number.


Example Bash Convert String to Number

Let's look at some examples of how to convert a string to a number in Bash:

1. Convert a Simple String to a Number

This script converts the string stored in the variable str to a number and prints the result.

#!/bin/bash

str="123"
number=$((str))
echo "The number is: $number"

In this script, the variable str is assigned the value '123'. The arithmetic expansion $(( )) converts the string to a number, and the result is stored in the variable number. The script then prints the number.

Convert a simple string to a number in Bash

2. Convert a User Input String to a Number

This script prompts the user to enter a string, converts the entered string to a number, and prints the result.

#!/bin/bash

read -p "Enter a number: " str
number=$((str))
echo "The number is: $number"

In this script, the user is prompted to enter a string, which is stored in the variable str. The arithmetic expansion $(( )) converts the string to a number, and the result is stored in the variable number. The script then prints the number.

Convert a user input string to a number in Bash

3. Convert a String from Command Output to a Number

This script converts the output of a command stored in the variable output to a number and prints the result.

#!/bin/bash

output=$(echo "456")
number=$((output))
echo "The number is: $number"

In this script, the variable output is assigned the result of a command that echoes '456'. The arithmetic expansion $(( )) converts the string to a number, and the result is stored in the variable number. The script then prints the number.

Convert a string from command output to a number in Bash

Conclusion

Converting a string to a number in Bash is a fundamental task for performing arithmetic operations on string inputs in shell scripting. Understanding how to convert strings to numbers can help you manage and process numeric data effectively in your scripts.