Introduction
Local variables help keep data inside a function so it doesn't affect the rest of the script.
local variable_name=value
my_function() {
local count=5
echo "Count is $count"
}my_function() {
local name="Alice"
echo "Hello, $name"
}my_function() {
local number
number=10
echo $number
}#!/bin/bash count=100 define_function() { local count=5 echo "Inside function, count = $count" } echo "Before function, count = $count" define_function echo "After function, count = $count"
local keyword do in a Bash function?local exist only inside the function where they are declared.local prevents changes outside the function.count inside a Bash function?local variable_name=value.local count=10 matches the correct syntax.#!/bin/bash
value=5
function test_func() {
local value=10
echo $value
}
test_func
echo $valuetest_func, value is local and set to 10, so echo $value prints 10.value remains 5 because local variable does not affect it.function example() {
local=5
echo $local
}local as a variable name conflicts with the reserved keyword local.local=5 tries to overwrite the keyword, causing a syntax error.local to achieve this?local counter inside the function creates a separate variable that does not affect the global one.export shares variables with child processes; declaring local outside function is invalid.local counter inside the function and increment it there. -> Option BPass the test and this pattern moves unknown