0
0
Bash Scriptingscripting~15 mins

Local variables (local keyword) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
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 30
Create a function called calculate_total that uses a local variable total
Use a for loop inside the function to sum the prices
Call 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
1
Create the prices array
Create a bash array called prices with the values 10, 20, and 30.
Bash Scripting
Need a hint?

Use parentheses to create a bash array: prices=(10 20 30).

2
Create the calculate_total function with a local variable
Create a function called calculate_total that declares a local variable named total and sets it to 0.
Bash Scripting
Need a hint?

Define the function with calculate_total() { ... } and inside it write local total=0.

3
Sum the prices inside the function using a for loop
Inside the calculate_total function, use a for loop with variable price to iterate over ${prices[@]} and add each price to the local total variable.
Bash Scripting
Need a hint?

Use for price in "${prices[@]}"; do ... done and update total inside the loop.

4
Call the function and print the total
Call the calculate_total function, then print the value of total outside the function using echo. Note: Since total is local, declare a global total variable before calling the function and update it inside the function by returning the value.
Bash Scripting
Need a hint?

Use echo "$total" inside the function to output the sum, then capture it with total=$(calculate_total) and print it with echo "$total".