Bird
0
0

You want to write a Bash function that increments a counter variable without affecting the global variable of the same name. Which approach correctly uses local to achieve this?

hard🚀 Application Q15 of 15
Bash Scripting - Functions
You want to write a Bash function that increments a counter variable without affecting the global variable of the same name. Which approach correctly uses local to achieve this?
AIncrement the global variable directly without declaring local.
BDeclare <code>local counter</code> inside the function and increment it there.
CUse <code>export counter</code> inside the function before incrementing.
DDeclare <code>counter</code> outside the function and use <code>local</code> globally.
Step-by-Step Solution
Solution:
  1. Step 1: Understand local variable purpose

    Declaring local counter inside the function creates a separate variable that does not affect the global one.
  2. Step 2: Check other options

    Incrementing global directly changes global variable; export shares variables with child processes; declaring local outside function is invalid.
  3. Final Answer:

    Declare local counter inside the function and increment it there. -> Option B
  4. Quick Check:

    Local inside function isolates variable changes [OK]
Quick Trick: Use 'local' inside function to isolate variable changes [OK]
Common Mistakes:
MISTAKES
  • Modifying global variable unintentionally
  • Misusing export for local scope
  • Declaring local variables outside functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes