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: 

Then I got the following error:

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:
Admin Dirask Community
4380

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:

Run in command line:

Output:

Note:

As you can see, the message variable is not visible outside the scope leaving outside loop:  

0 commentsAdd 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