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
Related
I'm trying to add up all numbers inputted by a user, however there is no limit on how many numbers a user can input for the addition. How do I code this in linux shell script?
I have this so far:
firstNumber=0
secondNumber=0
number=0
echo Please enter two numbers to add up
read firstNumber
read secondNumber
echo Would you like to keep adding numbers? YES OR NO
read answer
if answer = YES
then
echo Please add another number
read number
echo $(($firstNumber +$secondNumber + $number))
fi
while answer = NO
do
echo $(($firstNumber + $secondNumber))
done
as #dash-o recommended, a simple entry sequence ended with ENTER is the most simple approach:
#!/usr/bin/env sh
sum=0
echo "Please enter integer numbers to add, or just RETURN to end."
while read -r number && [ -n "$number" ]; do
if [ "$number" -eq "$number" ] 2>/dev/null; then
sum=$((sum + number))
echo "Sum is: $sum"
else
echo "$number is not a valid integer. Try again..." >&2
fi
done
Or to allow multiple integers entry per line:
#!/usr/bin/env sh
# Save the shell's options state
shelloptions="$(set +o)"
# Disable globbing to prevent filename expansion in parameters
set -o noglob
sum=0
echo "Please enter integer numbers to add, or RETURN to end."
# Read lines until empty REPLY
while read -r && [ -n "$REPLY" ]; do
# Split $REPLY as parameters
# Globbing is turned-off so filenames will not mess with entries
# shellcheck disable=SC2086 # Explicitly intended word splitting
set -- $REPLY
# Iterate numbers from the parameters array
for number in "$#"; do
# If $number is a valid integer
if [ "$number" -eq "$number" ] 2>/dev/null; then
sum=$((sum + number))
else
echo "$number is not a valid integer." >&2
fi
done
echo "Sum is: $sum"
done
# Restore the shell's options state
eval "$shelloptions"
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
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
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 =.
This question already has answers here:
What are the special dollar sign shell variables?
(4 answers)
Closed 3 years ago.
This Nagios script uses ${1} and ${*} like so
if [ "${1}" ]; then
if [ "${ERRORSTRING}" ]; then
echo "${ERRORSTRING} ${OKSTRING}" | sed s/"^\/ "// | mail -s "$(hostname -s): ${0} reports errors\
" -E ${*}
fi
else
if [ "${ERRORSTRING}" -o "${OKSTRING}" ]; then
echo "${ERRORSTRING} ${OKSTRING}" | sed s/"^\/ "//
exit ${ERR}
else
echo no zpool volumes found
exit 3
fi
fi
Question
What does ${1} and ${*} do?
The command-line arguments $1, $2, $3,...$9 are positional parameters, with $0 pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9 as the arguments to the command.
"$*" special parameter takes the entire list as one argument with spaces between and the "$#" special parameter takes the entire list and separates it into separate arguments.
Suppose test.sh given below:
#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $#"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
Quoting from Special Parameters in the manual:
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word
with the value of each parameter separated by the first character of
the IFS special variable. That is, "$*" is equivalent to "$1c$2c…",
where c is the first character of the value of the IFS variable. If
IFS is unset, the parameters are separated by spaces. If IFS is null,
the parameters are joined without intervening separators.
$1 refers to a Positional Parameter.
Assume the following script:
echo "${1}"
echo "${*}"
Upon invoking by saying:
bash scriptname foo bar baz
it would produce:
foo
foo bar baz
Now observe the effect of the variable IFS. Given the script:
IFS=
echo "${1}"
echo "${*}"
echo "${#}"
Invoking it by saying:
bash scriptname "foo:hey you" bar baz
would produce:
foo:hey you
foo:hey youbarbaz
foo:hey you bar baz
$1 is used(to display or to get input for user interactively) to display First parameter.
$* is used to show all parameters entered.
# cat schecking.sh
#!/bin/bash
echo "All values:" "$*"
echo "Total number of Parameter(s) :" "$#"
# ./schecking.sh
All values:
Total number of Parameter(s) : 0
# ./schecking.sh It will help us to check
All values: It will help us to check
Total number of Parameter(s) : 6
# cat schecking.sh
#!/bin/bash
echo "First value is:" $1
echo "All values:" "$*"
echo "Total number of Parameter(s) :" "$#"
# ./schecking.sh It will help us to check
First value is: It
All values: It will help us to check
Total number of Parameter(s) : 6