BASH shell question, variable sustitution $1... command line args
Hi everyone,
I have a need to sum command line arguments in either a while or until loop. (easy to do in a for loop, but can't use one). Given the command line; 'script.sh 10 20 30 40' I must sum the values of $1 thru $4 but having trouble getting the substitution right, I've tried TOTAL=$(($TOTAL+$\$COUNTER)) TOTAL=$(($TOTAL+${$COUNTER})) trying to expand $\$COUNTER to, say $1, and add the value to TOTAL but can't seem to get it right. Any advise is welcome |
Show us your code so far. As part of a general soln, lookup the 'shift' cmd in bash...
http://linux.die.net/abs-guide/othertypesv.html |
#!/bin/bash
# sum_until.sh # Author: Mark Emry # Created: 4/17/2011 # Modified: 4/17/2011, # Purpose: until loop exercise # Description: sums numbers in a until loop clear echo echo NUMS="$@" TOTAL=0 TNUMS="$#" COUNT=1 until [ $COUNT -gt $TNUMS ] do TOTAL=$(($TOTAL+${$COUNT})) COUNT=$(($COUNT+1)) done echo "$NUMS = $TOTAL" #end BTW, thanks for the link. I modified the script to use the shift command like so; until [ $COUNT -gt $TNUMS ] do TOTAL=$(($TOTAL+$1)) shift COUNT=$(($COUNT+1)) done and that works just fine. Still wondering about my original methodology, is it even possible? |
Quote:
Code:
foo$ cat echoparms If I were to write a shell script to sum all arguments it would look a little different. I think what you're doing may work okay for you, but it could be simpler. HTH Edit This question reminds me of some of my school assignments. For extra credit, can you tell why my loop runs one more iteration than needed? ;) |
I have two queries for you:
1. Do you have to change all the standard variables ($#, $@ and so on) to new variable names? 2. You seem to use the arithmetic brackets (()) for some things but not others? As you have provided your current solution, you may also consider: Code:
#!/bin/bash |
You don't put $ in front of variables inside arithmetic expressions.
|
Quote:
Code:
foo$ i=1 Quote:
|
Quote:
I also didn't know that for if statements, you can omit the "$" from in front of "((" and it will evaluate if 1 is returned. I always did it like this: Code:
if [ $(( a == b )) '!=' 0 ] |
Quote:
Quote:
I think I explained that right :p To be fair, Bash is quite sophisticated and has many non-obvious constructs. |
All times are GMT -5. The time now is 04:44 AM. |