Bash Local Variable
Variables in Bash are global by default, even when they are set inside a function.
The local keyword makes a variable that only exists inside the function, so it does not change a variable with the same name outside.
local keeps the outside value
Save this as scope.sh:
#!/bin/bash
name="Tove"
change() {
local name="Linus"
echo "Inside: $name"
}
change
echo "Outside: $name"
Run it:
./scope.sh
Inside: Linus
Outside: Tove
Without local
Save this as global.sh. Without local, the function changes the outside variable:
#!/bin/bash
name="Tove"
change() {
name="Linus"
}
change
echo "Outside: $name"
Run it:
./global.sh
Outside: Linus