How to Assign Float to Variable in Bash Script? [2 Methods]

When dealing with float variables, Bash has some limitations. However, there are workarounds using external tools like bc and awk that enable you to perform calculations involving decimals. In this article, I will explore different ways to assign float to a variable in the Bash Script so that you can do mathematical operations using float values.

Key Takeaways

  • Understanding the Significance of Float Variables in Arithmetic Operation.
  • Using printf and awk commands to display the assigned float variable in a bash script.

Free Downloads

Why Do We Need to Pay Special Attention to Float Variables?

Let’s first understand the problem to assign float to a variable in bash. To calculate the summation of two values, follow the step described below to create an executable file.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file in Nano:

nano float_problem.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • float_problem.sh: Name of the file.

❸ Copy the script mentioned below:

#!/bin/bash
a=$1
b=$2

#doing the arithmetic operation
let sum=a+b

#displaying the output
echo "The addition of two given numbers is: $sum"

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

chmod u+x float_problem.sh
EXPLANATION
  • chmod: is used to change the permissions of files and directories.
  • u+x: Here, u refers to the “user” or the owner of the file and +x specifies the permission being added, in this case, the “execute” permission. When u+x is added to the file permissions, it grants the user (owner) permission to execute (run) the file.
  • float_problem.sh: is the file name to which the permissions are being applied.

❻ Run the script by using the following commands:

./float_problem.sh 4 6
./float_problem.sh 2.1 4.13

syntax error in float variableNow the question is why this syntax error occurs when I pass the float value as an argument. The reason is Bash, by default, treats variables as strings and does not have built-in support for floating-point arithmetic. Bash primarily focuses on integer arithmetic. Due to the limitations of Bash, it requires additional steps or external tools like bc or awk commands to handle floating-point values properly.

Here is the modified code given below to solve this issue.

#!/bin/bash
a=$1
b=$2

#doing the arithmetic operation
sum=$(echo "$a+$b" | bc)

#displaying the output
echo "The addition of two given numbers is: $sum"
EXPLANATION

Here the first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script. Then the Bash script takes two arguments, a and b, from the command line. It performs an arithmetic operation to add these two numbers using the bc commandline calculator. The result is stored in the variable sum, which is then displayed as the output using the echo command.

Now run the script by using the following commands as below:

./float_problem.sh 4 6
./float_problem.sh 2.1 4.13

rectifying the syntax error of float variableAs the image depicts above, both integer and float value return their output.

2 Different Methods to Assign Float to Variable & Display Output Using Bash Scripts

In Bash, assigning float is not a problem at all. It is a straightforward process. You can simply choose an appropriate variable name and store the value within it. However, performing algebraic operations can be a bit tricky since Bash primarily handles integers. You can utilize external programs like bc or awk in this regard. Here, I have demonstrated two ways to display the assigned float variable.

You can read our Comparative Analysis of Methods to distinguish between these two methods and best pick one for your needs.

Method 1: Assigning Float Variable and Displaying with the printf Command

In our first method, I will provide an example of assigning a float variable and displaying it using the printf command in Bash. Follow the script which I am going to provide below to accomplish the task.

You can follow the steps described in the 1st section, to save & make the script executable.

Script (float_printf.sh) >

#!/bin/bash

# Prompt the user to enter a float value
read -p "Enter a float value: " float_value

# Print the float value using printf
printf "Float value: %.2f\n" "$float_value"
EXPLANATION

The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script. The read -p command displays the prompt message, waits for the user to enter a float value, and then prints the entered value with two decimal places. The %.2f format specifier in printf ensures that the float value is displayed with two decimal places.

Run the script by using the following command:

./float_printf.sh

printf CommandThe above image depicts that the prompt takes 23.4 as a float value and returns it in the next line.

Method 2: Using Text Processing Tool awk to Assign Float to Variable

The awk command is a powerful text processing tool that can also perform arithmetic operations, including working with floating-point numbers. Here’s an example of using awk to assign a float value to a variable and display it. Follow the script provided below to do the same.

You can follow the steps described in the 1st section, to save & make the script executable.

Script (float_awk.sh) >

#!/bin/bash

# Prompt the user to enter a float value
read -p "Enter a float value: " float_value

# Use awk to perform floating-point arithmetic
result=$(awk -v x="$float_value" 'BEGIN {printf "%.2f", x * 2.5}')

# Print the result
echo "Result: $result"
EXPLANATION

The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script. The read -p command displays the prompt message and waits for the user to enter a float value. Next, the awk command is used to perform floating-point arithmetic. The –v x=”$float_value” option passes the value of float_value as a variable x to the awk command. Within the BEGIN block, printf “%.2f”, x * 2.5 performs the multiplication of x by 2.5 and formats the result to two decimal places. The calculated result is then assigned to the result variable using command substitution. Finally, the echo command is used to print the output.

Use the following command to run the script:

./float_awk.sh

Text Processing Tool awk to Assign FloatHere, the prompt takes 2.5 as the input value and then returns 6.25, after doing arithmetic operation.

Comparative Analysis of Methods

Now let’s compare assigning float variables and displaying them with the printf command in a Bash script and using the text processing tool awk to manipulate float values in the Bash script.

Methods Pros Cons
Method 1
  • With printf, you can control the number of decimal places to be displayed using format specifiers like %f, %.2f, etc.
  • Similar to the C language, using printf in Bash does not provide advanced data manipulation capabilities on floats within the print statement itself.
Method 2
  • awk has built-in variables like NF (number of fields), NR (number of records), etc., which can be useful for data processing tasks in the Bash script.
  • Utilizing awk within a Bash script introduces an extra layer of complexity compared to using printf directly.

In summary, the choice between using printf in Bash and awk to manipulate float values depends on the specific requirements of your script. If you need to perform more advanced data manipulation on float values, method 2 might be a better choice. However, if you only need to display float values with specific formatting, using method 1 directly in Bash is simpler and more straightforward.

Conclusion

In this article, I have explored different methods to assign float values to variables in Bash scripts. Despite Bash’s limited support for floating-point arithmetic, I have demonstrated workarounds using external tools like awk, and the printf command to achieve accurate and flexible float assignments. However, if you have any queries related to this article, feel free to comment below.

People Also Ask

How do I declare a float in bash?
In Bash, you cannot directly declare a variable with a specific data type, including float. Bash treats all variables as strings by default. However, you can work with float values by using external commands like bc or awk for arithmetic operations and calculations.
How to initialize a value in a shell script?
In a shell script, you can initialize a value by assigning it directly to a variable using the equal sign (=). For example, variable_name=value initializes the variable variable_name with the value.
How to use floats in bash?
To use floats in Bash, you can leverage external tools like bc or awk for floating-point arithmetic. These tools allow you to perform calculations with decimal values and store the results in variables.
How do you assign a float to an int variable?
In Bash, you cannot directly assign a float to an int variable because Bash variables do not have explicit data types. However, you can convert a float to an integer by using techniques like rounding, truncation, or extracting the integer part of the float value. The specific method depends on your requirements for handling the float-to-int conversion.

Related Articles


<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial

Rate this post
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment