Bird
0
0

You want to write a Bash function sum that takes two numbers as arguments and prints their sum. Which script correctly calls the function and prints the result?

hard🚀 Application Q15 of 15
Bash Scripting - Functions
You want to write a Bash function sum that takes two numbers as arguments and prints their sum. Which script correctly calls the function and prints the result?
A<pre>sum() { echo $(($1 + $2)) } sum 3 5</pre>
B<pre>sum() { echo $1 + $2 } sum 3 5</pre>
C<pre>sum() { echo $((1 + 2)) } sum 3 5</pre>
D<pre>sum() { echo $1 $2 } sum 3 5</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand arithmetic evaluation in Bash

    To add numbers, use $((expression)). Inside, use $1 and $2 for arguments.
  2. Step 2: Check each option's output

    sum() {
      echo $(($1 + $2))
    }
    sum 3 5
    correctly sums $1 + $2.
    sum() {
      echo $1 + $2
    }
    sum 3 5
    prints literal string with plus sign.
    sum() {
      echo $((1 + 2))
    }
    sum 3 5
    adds 1 and 2 literally, ignoring arguments.
    sum() {
      echo $1 $2
    }
    sum 3 5
    prints arguments separated by space.
  3. Final Answer:

    sum() { echo $(($1 + $2)) } sum 3 5 -> Option A
  4. Quick Check:

    Use $(( $1 + $2 )) for sum [OK]
Quick Trick: Use $(( $1 + $2 )) to add arguments inside function [OK]
Common Mistakes:
MISTAKES
  • Printing arguments without arithmetic evaluation
  • Using fixed numbers instead of arguments
  • Confusing string concatenation with addition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes