Addition of 2 numbers in shell script dynamically - linux

I'm trying to take input from user and then based on that input either addition operation will be performed or subtraction will be performed. Choice 1 is for addition and 2 is for subtraction. The error I'm getting is this:
number.sh: line 12: d: command not found
(for addition line 12)
number.sh: line 17: d: command not found
(for subtraction line 17)
Here is the code:
#!/bin/bash
echo "enter choice"
echo "enter 1 for addition"
echo "enter 2 for subtraction"
read a
echo "entered choice is" $a
echo "now enter 2 numbers"
if [ $a = 1]; then
read b
read c
d = `expr $b + $c`
echo "addition of 2 numbers is" $d
elif [ $a = 2]; then
read b
read c
d = `expr $b - $c`
echo "subtraction of 2 numbers is" $d
else
echo "enter valid choice"
fi

You have extra spaces around your assignments and missing spaces around your [] expressions. Here's a corrected version. Note that when you use two read calls, you need a newline in between when giving the input. That is, you have to type 1 <Enter> 2 <Enter> 3 <Enter> on the command line to get a result of 5.
#!/bin/bash
echo "enter choice"
echo "enter 1 for addition"
echo "enter 2 for subtraction"
read a
echo "entered choice is" $a
echo "now enter 2 numbers"
if [ $a = 1 ]; then
read b
read c
d=`expr $b + $c`
echo "addition of 2 numbers is" $d
elif [ $a = 2 ]; then
read b
read c
d=`expr $b - $c`
echo "subtraction of 2 numbers is" $d
else
echo "enter valid choice"
fi

There should be no spaces around the = sign on line 12 and 17. Remove those spaces.
In bash, there should be no spaces around the assignment operator =.

Related

how can I complete this?

the question is:
use a script to take two numbers as arguments and output their sum using (i) bc, (ii) expr. include error-checking to test whether two arguments were entered.
My answer:
echo " The first number is"
read a
echo " The second number is"
read b
c=`echo "scale=2; $a + $b"|bc`
echo _____________________________________________
echo " The sum of two numbers using bc:$c "
echo
d=`expr $a + $b`
echo " The sum of two numbers using expr:$d "
echo _____________________________________________
I can't include the error checking in this program. how can i do it? please help!
Get the numbers from arguments $1 and $2, not by prompting for input.
Check the number of arguments using $#.
if [ $# -ne 2 ]
then
echo "Usage: $0 number1 number2" >&2 # write error message to stderr
exit 1
fi
a=$1
b=$2
# rest of your script goes here

Making a script to take input from a user and use error checking to test if two arguments were entered: Linux

My Linux class just started to begin scripting and I am having trouble with one of my questions. The question is as follows: Use a script to take two numbers as arguments and output their sum using bc.
This is my first script. To get the script to execute you need to do chmod +x filename
This is what I have so far:
#!/bin/bash
read -p "Enter in a numeric value: " num1
read -p "Enter in a second numeric value: " num2
if [ $# -ne 2 ] ; then
echo "Enter in two numeric arguments"
else
echo "The sum of the entered values are: "
echo "$num1 + $num2"|bc
fi
I keep running into an error. When I enter in two values it displays "Enter in two numeric arguments". It shouldn't do that because if I enter in two values, the if statement will evaluate to false and go to the else statement. Is my logic wrong or am I approaching this the wrong way?
You can use a while loop and break.
n=0
ex=""
while [ 1 ]
do
read -p "Enter read in a numeric value" num
n=$(( n + 1))
if [[ $n -eq 2 ]]
then
ex=${ex}${num}
echo "Sum of the two values are"
echo ${ex} | bc
break
else
ex=$num" + "
fi
done

Print error for missing argument

I am trying to write a script which will check number of arguments for first and second number; if both variable entered, it will do the calculation; if one argument is missing, it will print error message.
Here what I've done so far:
#!/bin/bash
echo -n "Enter the first number: "
read num1
echo -n "Enter the second number: "
read num2
if [ $# -le 1 ]; then
echo "Illegal number of arguments"
exit
else
echo "The sum is: " $(( num1 + num2 ))
fi
I am always getting error message even though I enter both of the numbers. What am I missing? Please help.
Test Your Assigned Variables, Not Positional Parameters
Your variables num1 and num2 aren't positional parameters, and so the special parameter $# is probably not what you think it is. You should change your conditional to check that both variables are set. For example:
declare -i num1 num2
read -p 'Enter the first number: ' num1
read -p 'Enter the second number: ' num2
if [ -z "$num1" ] || [ -z "$num2" ]; then
echo "Illegal number of arguments" >&2
else
echo "The sum is: $((num1 + num2))"
fi
Looks like you are messing up command line arguments and variables you are reading interactively. $# has nothing to do with variables you declared and/or read from command line. It is the number of command line arguments. You need to check the variables you attempted to read from console:
#!/bin/sh
echo -n "Enter the first number: "
read num1
echo -n "Enter the second number: "
read num2
[ -z $num1 ] || [ -z $num2 ] && echo "Illegal number of arguments" && exit 1
echo "The sum is: " $(( num1 + num2 ))
On the other hand, if you really want to check command line arguments, the script will be even simpler:
#!/bin/sh
[ -z $2 ] && echo "Illegal number of arguments" && exit 1
echo "The sum is: " $(( $1 + $2 ))
Here $1 refers to the first argument, $2 refers to the second argument and so on. $0 refers to the name of the script itself.
So, the way you have your program setup right now, it takes input through the read command, but that isn't the same as passing in an argument.
You pass an argument through the CLI, for instance:
./sum.sh 5 2 # => 7
Where sum.sh is the name of the file and 5 and 2 are your arguments.
So, the reason you keep getting "Illegal number of arguments" is because in bash the $# variable holds the number of arguments, but since you're reading the values in from the code, $# will always less than 1 because no arguments have been provided.
What I think you're looking for is something like this:
#!/bin/bash
if [ $# -le 1 ]; then
echo "Illegal number of arguments"
exit
else
echo "The sum is: " $(( $1 + $2 ))
fi
This article is pretty good if you want to learn more: http://www.bashguru.com/2009/11/how-to-pass-arguments-to-shell-script.html

Linux if-else not working

i write one linux code for Fibonacci series(0 1 1 2 3 5 8) but when i run its always showing me else statement.
#!/bin/bash
#This program will show series of Fibonacci numbers upto user input.
echo -n "Enter the number for Fibonacci series: "
read num
if [ $# = 1 ]
then
x1 = 0
x2 = 1
echo "The Fibonacci series for the number $num is: "
for (( y=0;$y<num; y=$y+1 ))
do
echo -n "$x1 "
x2 = $(( $x2 + $1 ))
x1 = $(( $x2 - $x1 ))
done
else
echo "Input is wrong"
fi
if i remove if satement then i got error of line 10 and 11 and of for loop
I'm not sure why you're checking the number of arguments, but you either need to provide one argument or change it to check for zero arguments. Also you have a few spaces that will cause problems. You'll need to remove those. Lastly, as #bnaecker mentioned, you'll want to use -eq instead of = when comparing numerical equality.
#!/bin/bash
#This program will show series of Fibonacci numbers upto user input.
echo -n "Enter the number for Fibonacci series: "
read num
if [ $# = 0 ]
then
x1=0
x2=1
echo "The Fibonacci series for the number $num is: "
for (( y=0;$y<num; y=$y+1 ))
do
echo -n "$x1 "
x2=$(($x2 + $1))
x1=$(($x2 - $x1))
done
else
echo "Input is wrong"
fi

Building simple calculator in BASH

I am learning Bash Shell Scripting as a section from the Linux Foundation LFS101x.2 and there is a Lab to create a simple Bash calculator.
The Lab details are found here:
Lab 5
I'm trying to run the script by:
$ ./bashShellScriptingLab5.sh s 15 5
The error message is:
Welcome to Calculator!
./bashShellScriptingLab5.sh: line 39: syntax error near unexpected token `exit'
./bashShellScriptingLab5.sh: line 39: ` exit 0'
Here is my bashShellScriptingLab5.sh:
#!/bin/bash
echo "Welcome to Calculator!"
if [ $# != 3 ];
then
echo "Usage:"
echo "Please enter a/s/m/d and two integers"
exit 1
fi
addition () {
echo "The result of adding " + $2 + " and " + $3 + " is:"
d = expr $2 + $3
echo $d
}
subtraction () {
echo "The result of subtracting " + $2 + " and " + $3 + " is:"
d = expr $2 - $3
echo $d
}
multiplication () {
echo "The result of multiply " + $2 + " and " + $3 + " is:"
d = expr $2 * $3
echo $d
}
division () {
echo "The result of dividing " + $2 + " and " + $3 + " is:"
d = expr $2 / $3
echo $d
}
if [[ "$1" = "a" ]]
then
addition()
exit 0
elif [[ "$1" = "s" ]]
then
subtraction()
exit 0
elif [[ "$1" = "m" ]]
then
subtraction()
exit 0
elif [[ "$1" = "d" ]]
then
division()
exit 0
else
echo "Usage:"
echo "Please enter a/s/m/d and two integers"
exit 1
fi
Quit a few errors here, I'll run through them and then show an example of a working script.
Firstly you appear to have made some assumptions about how functions work.
Calls to functions do not require the ()
addition()
Also you are trying to use global positional parameter in your functions which will not work as they have their own, so the call to the function should pass in what you want
addition $2 $3
With this in mind the inside of the function will also have to change
echo "The result of adding " + $1 + " and " + $2 + " is:"
As you can see we now use $1 and $2 as we are using the first and second parameter to the function,not the script!
Inside the function there are few more problems
d = expr $2 + $3
Spaces have a purpose in bash so will interfere with the = sign. The command is read as d(function/file/script/exe/whatever) and then the equals is a parameter to this. Thus you cannot have spaces between the = and both sides, so it should be written as
d=expr $2 + $3
Although this will still cause a compile error due to the spaces after expr.So we will need to run this in a subshell to assign it to d
d=$(expr $2 + $3)
Although personally i would just go for bash arithmetic
d=$(($2 + $3))
So if you change all of these in your script it should work, was gonna pad this out a bit more but ran out of time.
Working code
#!/bin/bash
echo "Welcome to Calculator!"
if [ $# != 3 ];
then
echo "Usage:"
echo "Please enter a/s/m/d and two integers"
exit 1
fi
addition () {
echo "The result of adding " + $1 + " and " + $2 + " is:"
d=$(($1 + $2))
echo $d
}
subtraction () {
echo "The result of subtracting " + $2 + " and " + $3 + " is:"
d=$(($1-$2))
echo $d
}
multiplication () {
echo "The result of multiply " + $1 + " and " + $2 + " is:"
d=$(($1*$2))
echo $d
}
division () {
echo "The result of dividing " + $1 + " and " + $2 + " is:"
d=$(($1/$2))
echo $d
}
if [[ "$1" = "a" ]]
then
addition $2 $3
exit 0
elif [[ "$1" = "s" ]]
then
subtraction $2 $3
exit 0
elif [[ "$1" = "m" ]]
then
multiplication $2 $3
exit 0
elif [[ "$1" = "d" ]]
then
division $2 $3
exit 0
else
echo "Usage:"
echo "Please enter a/s/m/d and two integers"
exit 1
fi
To call a function in bash you don't need the parens, those are what's throwing you off. Instead just do
if [[ "$1" = "a" ]]
then
addition
exit 0
elif [[ "$1" = "s" ]]
then
subtraction
exit 0
elif [[ "$1" = "m" ]]
then
multiplication
exit 0
elif [[ "$1" = "d" ]]
then
division
exit 0
else
echo "Usage:"
echo "Please enter a/s/m/d and two integers"
exit 1
fi
Also, for option "m" you had been calling subtraction again, I changed that to multiplication
That will get you past this error, I think you'll find more after that though
Simple Calculator 1.0
clear
echo "(exp=**, div=/, mult=*, add=+, sub=-)"
echo "\"a/b\" returns only quotient (use no spaces)"
echo "\"a / b\" returns quotient and remainder (use spaces)"
echo " "
echo "Welcome to my Simple Calculator"
echo " "
read -p 'Enter a simple calculation: ' -a sC
answer=$((${sC[0]} ${sC[1]} ${sC[2]}))
echo " "
echo " "
if [ "${sC[1]}" != "/" ]
then echo "The answer is equal to $answer"
else answerRemainder=$((${sC[0]} % ${sC[2]}))
echo "The answer is equal to $answer remainder $answerRemainder"
fi
echo " "
echo " "
echo "Thank you for using Simple Calculator 1.0"
echo "Have a nice day!"
No spaces between two expressions returns calculations without remainders:
(exp=**, div=/, mult=*, add=+, sub=-)
"a/b" returns only quotient (use no spaces)
"a / b" returns quotient and remainder (use spaces)
Welcome to my Simple Calculator
Enter a simple calculation: 10/4
The answer is equal to 2
Thank you for using Simple Calculator 1.0
Have a nice day!
Space between "/" will return a remainder:
(exp=**, div=/, mult=*, add=+, sub=-)
"a/b" returns only quotient (use no spaces)
"a / b" returns quotient and remainder (use spaces)
Welcome to my Simple Calculator
Enter a simple calculation: 10 / 4
The answer is equal to 2 remainder 2
Thank you for using Simple Calculator 1.0
Have a nice day!
You can make the first expression as long as you want with no spaces and multiply a second expression that contains addition, subtraction, multiplication, or division:
Enter a simple calculation: 1000/4/2/5 * 4+1
The answer is equal to 101
Enter a simple calculation: 1000/4/2/5 *4-2
The answer is equal to 98
Enter a simple calculation: 1000/4/2/5 * 4*2
The answer is equal to 200
Enter a simple calculation: 1000/4/2/5 * 4/2
The answer is equal to 50
However, Simple Calculator doesn't support remainder division of a second expression that contains any calculations not surrounded with brackets:
If dividing a second expression with calculations the second expression must be surrounded with brackets in order to obtain the correct result:
Enter a simple calculation: 1000/4/2/5 / (4/2)
The answer is equal to 12 remainder 1
Brackets for the second expression are necessary!
1000/4/2/5 / 4/2 <---no brackets will return unpredictable results.
Answer should be 12 remainder 1, but will return 3 remainder 0.
Enter a simple calculation: 1000/4/2/5 / 4/2
The answer is equal to 3 remainder 0
Here in this case for remainder division, the brackets for the second expression are necessary.

Resources