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.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file in Nano:
nano float_problem.sh
- 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
- 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
Now 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"
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 command–line 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
As 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.
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) > 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: 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) > 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: 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.Method 1: Assigning Float Variable and Displaying with the printf Command
#!/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"
./float_printf.sh
The 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
#!/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"
./float_awk.sh
Here, the prompt takes 2.5 as the input value and then returns 6.25, after doing arithmetic operation.
Comparative Analysis of Methods
Methods
Pros
Cons
Method 1
Method 2
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
Related Articles
- How to Declare Variable in Bash Scripts? [5 Practical Cases]
- Bash Variable Naming Conventions in Shell Script [6 Rules]
- How to Assign Variables in Bash Script? [8 Practical Cases]
- How to Check Variable Value Using Bash Scripts? [5 Cases]
- How to Use Default Value in Bash Scripts? [2 Methods]
- How to Use Set – $Variable in Bash Scripts? [2 Examples]
- How to Read Environment Variables in Bash Script? [2 Methods]
- How to Export Environment Variables with Bash? [4 Examples]
<< Go Back to Variable Declaration and Assignment | Bash Variables | Bash Scripting Tutorial