Languages

Bash - how to create local variable inside loop?

3 points
Asked by:
Hiba-Tate
548

How can I create a local variable inside loop in Bash?

I was trying to print a message using local variable like this: 

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:

./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. 

1 answer
0 points
Answered by:
Hiba-Tate
548

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:

#!/bin/bash

# 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:

./script.sh

Output:

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 leaving outside loop:  

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join