Bash - how to create local variable inside loop?
How can I create a local variable inside loop in Bash?
I was trying to print a message
using local
variable like this:
xxxxxxxxxx
for i in 1 2 3; do
local message="index: $i"
echo "inside loop: $message"
done
echo "outside loop: $message"
Then I got the following error:
xxxxxxxxxx
./script.sh: line 4: local: can only be used in a function
Is there any way to do that? I don't want the message
variable to be accessable outside the for
loop scope.
No, you can only use local
keyword inside functions.
Note:
A variable declared as
local
is visible only within the block of code in which it has been declared. It has local scope. Local variable in a function has meaning only within that function block.
Solution
If you really want to use local
, you have to create a scope. I would recommend creating and calling a function.
script.sh
file:
xxxxxxxxxx
# Create function, scope for your code:
my_function() {
for i in 1 2 3; do
local message="index: $i"
echo "inside loop: $message"
done
}
my_function # calls the function (displays local message)
echo "outside loop: $message" # message is not available here
Run in command line:
xxxxxxxxxx
./script.sh
Output:
xxxxxxxxxx
inside loop: index: 1
inside loop: index: 2
inside loop: index: 3
outside loop:
Note:
As you can see, the
message
variable is not visible outside the scope leavingoutside loop:
.