In: Computer Science
Create a bash script that takes numbers as parameters, calculates sum and prints the result. If no parameters passed, prompt a user (only one time) to enter numbers to sum and print the result.
Step 1-
Create function with Parameters:
Bash can’t declare function parameter or arguments at the time of function declaration. But you can use parameters in function by using other variable. If two values are passed at the time of function calling then $1 and $2 variable are used for reading the values. Create a file named ‘function|_parameter.sh’ and add the following code. Here, the function, ‘Rectangle_Area’ will calculate the area of a rectangle based on the parameter values.
#!/bin/bash
Rectangle_Area() {
area=$(($1 * $2))
echo "Area is : $area"
}
Rectangle_Area 10 20
Run the file with bash command.
$ bash function_parameter.sh
Step 2-
Add Two Numbers:
You can do the arithmetical operations in bash in different ways. How you can add two integer numbers in bash using double brackets is shown in the following script. Create a file named ‘add_numbers.sh’ with the following code. Two integer values will be taken from the user and printed the result of addition.
#!/bin/bash
echo "Enter first number"
read x
echo "Enter second number"
read y
(( sum=x+y ))
echo "The result of addition=$sum"
Run the file with bash command.
$ bash add_numbers.sh