Bird
0
0

How would you write a bash function total that sums all its numeric arguments and prints the result?

hard🚀 Application Q9 of 15
Bash Scripting - Functions
How would you write a bash function total that sums all its numeric arguments and prints the result?
Atotal() { sum=0; while read n; do sum=$((sum + n)); done; echo $sum; }
Btotal() { echo $(( $1 + $2 )); }
Ctotal() { let sum=$1+$2+$3; echo $sum; }
Dtotal() { sum=0; for n in "$@"; do sum=$((sum + n)); done; echo $sum; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand argument handling

    To sum any number of arguments, iterate over all arguments using "$@".
  2. Step 2: Accumulate sum

    Initialize sum=0, then add each argument to sum inside a loop.
  3. Step 3: Output the total

    After the loop, print the sum.
  4. Final Answer:

    total() { sum=0; for n in "$@"; do sum=$((sum + n)); done; echo $sum; } -> Option D
  5. Quick Check:

    Loop over "$@" to handle all arguments [OK]
Quick Trick: Use for loop over "$@" to sum all arguments [OK]
Common Mistakes:
MISTAKES
  • Only summing first two arguments
  • Using read loop without input redirection
  • Assuming fixed number of arguments

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes