checking variables + arithmetic operator help


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting checking variables + arithmetic operator help
# 1  
Old 12-01-2011
checking variables + arithmetic operator help

i'm trying to make a script to simply add numbers together

for example i have a file script file called add

[john@home ~] add 1 2 3 4 5
15

however i want the user to put at least 3 numbers so i did this
Code:
if [ $* -eq 2 ]
then
echo "please enter more than two numbers"
exit 1
fi

but it's telling me i have more than too arguments, how would i fix that?

the next part is that the essiental code is working, however i want to make a similar coding but i want the average of it instead of adding it all together
so i replaced "+" with "/" but doesn't work

here is my coding
Code:
total=0
for i in $*
do
total=`echo $(($total + $i))`
done

echo $total

thanks in advance
# 2  
Old 12-01-2011
The variable $* expands to each parameter from the command line. You want $# which is the number of parameters.

As for you example code, you don't need the echo nor the back ticks:

Code:
total=0
n=$#
while [[ -n $1 ]]
do
   total=$(( total + $1 ))
   shift
done
echo "total=$total  average=$(($total/$n))"

Bash cannot do floating point, but kshell can, so you can change the last line to the following if you want to use kshell and have a more percise average:

Code:
echo "total=$total  average=$(($total/$n.0))"

# 3  
Old 12-01-2011
i almost forgot this as well, which is implementing whether or not the user input is an actual number or not

so i did this along with the if statement

Code:
if [[ $# -eq 2 || $# != [0-9] ]]

so essentially if the user doesn't enter more than 2 numbers than it's invalid or if the user doesn't enter a number it's also invalid, but my coding isn't fulling working

for example:

add 1 2 3 x 5
11

the if statement doesn't seem to validate that i've enter a character of "x"
# 4  
Old 12-01-2011
You're trying to use $# in the wrong way for your check to ensure that they are all numbers. [icode[$#[/icode] evaluates just to the number of parameters on the command line. If the user entered '1 2 3 x 4 5 6' $# would be 7 and the second expression $# != [0-9] will always evaluate to true.

This would be an easy way to validate that each digit on the command line is a number:

Code:
#!/usr/bin/env ksh
total=0
n=$#
while [[ -n $1 ]]
do
    if [[ -n ${1//[0-9]/}  ]]       # replace all digits in x and if result isn't empty, fail
    then
        echo "abort: invalid parameter entered: $1"
        exit 1
    fi

   total=$(( total + $1 ))
   shift
done

if (( $n > 0 ))    # prevent div by zero issues
then
    echo "total=$total  average=$(($total/$n))"
fi

exit

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Invalid arithmetic operator on string concatenation

Hello. LEAP_VERSION="4.2" export ARRAY_MAIN_REPO_LEAP=('zypper_local' 'openSUSE-Leap-'"$LEAP_VERSION"'-Non-Oss' 'openSUSE-Leap-'"$LEAP_VERSION"'-Oss' 'openSUSE-Leap-'"$LEAP_VERSION"'-Update' 'openSUSE-Leap-'"$LEAP_VERSION"'-Update-Non-Oss')Seems that the - is interpreted as a numeric... (2 Replies)
Discussion started by: jcdole
2 Replies

2. Shell Programming and Scripting

BC calculation for floating (invalid arithmetic operator )

Hi, I wish to compare the CPU LOAD 1 min with 5mins and 15mins. If 1 min's CPU LOAd spike 3% compare to 5 mins or 15 mins CPU Load, it is warning. If 1 min's CPU LOAd spike 5% compare to 5 mins or 15 mins CPU Load, it is critical. However I received following code error, I google it and... (10 Replies)
Discussion started by: alvintiow
10 Replies

3. UNIX for Dummies Questions & Answers

Invalid arithmetic operator

Hi experts, I'm facing trouble with the below bash script, any help is appreciated #!/usr/bin/bash .. if (( "${date1}" > "${l_date1}" )) then echo "success" else echo "nothing" fi the variable date1 contains 08/06/2013 and l_date1 contains 10/08/2013 this small script to... (6 Replies)
Discussion started by: parpaa
6 Replies

4. Shell Programming and Scripting

PAssing variables to awk arithmetic

Hi all, I am wanting to pass variables from a file to an awk arithmetic formula. When I use the formula with the value it works well. As soon as I make these variables I get an inf (infinity) response. I can certainly echo the variables back and they look correct. My googling for answers has... (3 Replies)
Discussion started by: gafoleyo73
3 Replies

5. SCO

Stop boot system at "Checking protected password and checking subsystem databases"

Hi, (i'm sorry for my english) I'm a problem on boot sco unix 5.0.5 open server. this stop at "Checking protected password and checking subsystem databases" (See this image ) I'm try this: 1) http://www.digipedia.pl/usenet/thread/50/37093/#post37094 2) SCO: SCO Unix - Server hangs... (9 Replies)
Discussion started by: buji
9 Replies

6. Shell Programming and Scripting

Help with checking that 2 variables contain matching characters

hi i am writing a hangman script and am having trouble checking the correct letters against the word i need the script to compare the word against the letters guessed that are correct so once all the letters within the word have been guessed it will alow me to create a wining senario eg ... (3 Replies)
Discussion started by: lsecer
3 Replies

7. UNIX for Dummies Questions & Answers

syntax error: invalid arithmetic operator

hi, i have a bash script that i want to receive a a string from another bash file. But because the string has a dot in the middle it gives me an error. The error is in this line: let valor=$1 and the value passed is rules.txt the error is: let: valor=rules.txt: syntax error: invalid... (2 Replies)
Discussion started by: limadario
2 Replies

8. Shell Programming and Scripting

Need help with arithmetic expression using variables

Hi, I am trying to do a percentage calculation in a Bourne shell script. The following works fine, but when I try to subsitute the values 153824 and 246000 for variables (e.g. used and limit), I get errors. calc() { awk 'BEGIN {OFMT="%f"; print '"$*"'; exit}' } calc '(153824 /... (3 Replies)
Discussion started by: shorehil
3 Replies

9. Shell Programming and Scripting

Checking if file exists using a NOT operator and shell variable

Hi, I'm new to UNIX, at least shell programming and am having trouble figuring out a problem i'm having. In one section in my nested if statement, i want the program to test if the file does not exist, based on an argument supplied at the command line by the user. What i have is elif ; then... (3 Replies)
Discussion started by: rowlf
3 Replies

10. Shell Programming and Scripting

Checking variables

Firstly - aplogies to Vino I need to check wether or not a variable called DATE is actually a date by doing the following - checking it is all numeric and secondly checking if it is 8 digits long. Any help appreciated (10 Replies)
Discussion started by: penfold
10 Replies
Login or Register to Ask a Question