Using Local Variables with the local Keyword in Bash
📖 Scenario: You are writing a bash script to calculate the total price of items in a shopping list. You want to keep your calculations clean and avoid changing variables outside your function.
🎯 Goal: Build a bash script that uses a function with a local variable to calculate the total price of items without affecting variables outside the function.
📋 What You'll Learn
Create a bash array called
prices with the values 10, 20, and 30Create a function called
calculate_total that uses a local variable totalUse a
for loop inside the function to sum the pricesCall the function and print the total price outside the function
💡 Why This Matters
🌍 Real World
Using local variables in bash functions helps keep scripts clean and avoids accidental changes to important data outside functions.
💼 Career
Many automation and DevOps tasks use bash scripts where local variables prevent bugs and make code easier to maintain.
Progress0 / 4 steps