Bash & Shell Scripting (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What are Functions and the `local` keyword in Bash?
senior LevelCode ExampleSystem Design
In Simple Words: Functions group reusable blocks of commands:
- The
localKeyword: By default, all variables in Bash are global! Declaring a variable withoutlocalinside a function will overwrite global variables of the same name. - Always declare variables inside functions with
local:
bash
calculate_sum() {
local a="$1"
local b="$2"
echo "$((a + b))"
}
result=$(calculate_sum 10 20)