Bird
0
0

Consider this script:

hard🚀 Application Q9 of 15
Bash Scripting - Functions
Consider this script:
#!/bin/bash
count=0
increment() {
  local count=$((count + 1))
  echo $count
}
increment
increment
echo $count

What will be the output and why?
A1 2 2 because local count updates global count
B1 1 0 because local count shadows global count inside function
C0 0 0 because local count is not incremented
D1 2 0 because local count resets each call
Step-by-Step Solution
Solution:
  1. Step 1: Analyze local variable initialization each call

    Each call initializes local count as $((count + 1)), but count inside is local and uninitialized, so it uses global count which is 0, so local count becomes 1 each time.
  2. Step 2: Check output of each call and global count

    Each call prints 1, but since local count resets, second call also prints 1. Global count remains 0.
  3. Step 3: Verify options

    Only 1 1 0 because local count shadows global count inside function matches output 1 1 0 and explains that local count shadows global count inside function.
  4. Final Answer:

    1 1 0 because local count shadows global count inside function -> Option B
  5. Quick Check:

    Local variables reset each call = A [OK]
Quick Trick: Local variables reset each call, don't accumulate [OK]
Common Mistakes:
MISTAKES
  • Assuming local variable keeps value between calls
  • Thinking local updates global
  • Confusing variable scopes in arithmetic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes