Tuesday, July 28, 2009

Need help on unix C-shell script program?

#!/bin/csh


# This program will add integers


#


#


# add integer1 ..


#





# Check for argument


if ($#argv == 0 ) then


echo "usage: add integers"


exit 1


else


set input = $argv[*]


endif


#


set sum = 0


foreach var ( $input )


@sum = $sum + $input


end


#


echo "The sum total of the integers is $sum"


#


exit 0


#





Hi I am trying to make a program that adds all integers that are input.


ex. add 2 sum = 2


add 2 4 10 sum = 16





This is what i have for code but i keep getting the error "add: syntax error at line 18: `(' unexpected". If anyone could help me fix it i would appreciate it.

Need help on unix C-shell script program?
Your script needed three changes:





1) Double quoted the right hand side of the "set"


2) Added a space between "@" and "sum"


3) Correct the addition to use $var, not "$input"





With some indentation, the result is:





#!/bin/csh


# This program will add integers


#


#


# add integer1 ..


#





# Check for argument


if ($#argv == 0 ) then


   echo "usage: add integers"


   exit 1


else


   set input = "$argv[*]"


endif


#


set sum = 0


foreach var ( $input )


   @ sum = $sum + $var


end


#


echo "The sum total of the integers is $sum"


#


exit 0


#





To demonstrate that it works:





   $ add2.csh 1 2 3 4 5 6 7


   The sum total of the integers is 28


   $ add2.csh 2 4 6


   The sum total of the integers is 12











You *could* simplify by removing the "else" clause


and directly using "$argv" in the "foreach" stmt.


Those changes would leave your script as:





#!/bin/csh


# This program will add integers


#


#


# add integer1 ..








# Check for argument


if ($#argv == 0 ) then


   echo "usage: add integers"


   exit 1


endif





set sum = 0


foreach var ( $argv )


   @ sum = $sum + $var


end





echo "The sum total of the integers is $sum"


exit 0
Reply:in unix shell scripting please make sure that you have input right spaces becauise this is the major problem in unix even a no space or an extra space created a problem

phone cards

No comments:

Post a Comment