snaper snaper - 7 months ago 9
Bash Question

Arguments not found in shell script

I am trying to write my first shell script for a class. The goal is to take a list of integers as a command line argument and display their squares and the sum of the squares. I am getting an error that the arguments are not being found.

This is the piece that is giving the error that the arguments are not found:

sumsq=0 #sum of squares
int=0 #Running sum initialized to 0
count=0 #Running count of numbers passed as arguments

while [ $# != 0 ]
do
numbers[$int]=`expr $1` #Assigns arguments to integers
let square=`expr $1*$1` #Operation to square arguments
squares[$int]=$square #Calc. square of each argument
sumsq=`expr $sumsq + $square` #Add square to total
count=`expr $count + 1` #Increment count
shift #Remove the used argument
int=`expr $int + 1` #Increment to next argument

done


I am using dash shell.

Answer

It seems that you are a beginner, some good pointers to start learning:

FAQ: http://mywiki.wooledge.org/BashFAQ
Guide: http://mywiki.wooledge.org/BashGuide
Ref: http://www.gnu.org/software/bash/manual/bash.html
http://wiki.bash-hackers.org/
http://mywiki.wooledge.org/Quotes
Check your script: http://www.shellcheck.net/

And avoid people saying to learn with tldp.org web site, the tldp bash guide is outdated, and in some cases just plain wrong.

There's many things in your code that can be improved. Better learn the good way as soon as possible. Your code looks 80's =)


A corrected version (not tested) with a more bashy way to do things:

sumsq=0 #sum of squares  
int=0 #Running sum initialized to 0  
count=0 #Running count of numbers passed as arguments  

while (($# != 0 )); do 
    numbers[$int]=$1            #Assigns arguments to integers array
    square=$(($1*$1))           #Operation to square argument first arg by itself
    squares[$int]=$square       #Square of each argument
    sumsq=$((sumsq + square))   #Add square to total
    count=$((count++))          #Increment count
    shift                       #Remove the used argument
done
Comments