Problems with Bash arrays. I’m just trying to understand a few things and… | by Teri Radichel | Biting Bugs | January 2024

esteria.white

Just figured out a few things and wrote them down for myself and anyone else facing similar issues.

I don’t necessarily consider myself a bash expert but I feel like I have to become one.

Initially I just wanted to write a POC in bash and move it to another language. But I’ve been writing this POC for about a year now…

So I’m currently working with bash arrays and there are some issues. There are different old and new ways to declare or use bash arrays. There are so many articles showing the old ways because bash has been around for so long. I’m going to stick to the newer methods because I *hope* you’re not using outdated software if you use my code for secure deployments with proper governance.

First of all, I recently discovered the term “local” because none of the older articles refer to it. This is a very important construct because it helps you keep variables specific to a function and not overwrite them with another function that has a variable of the same name.

I’ve written about the importance of using proper scoping in programming languages ​​in other articles and I thought bash just wasn’t capable of doing it, but it is! I had so many weird bugs because I had a function calling a function and I was using the same name in both. Although I understand all this which unsettled me for a while in some cases.

To use local as soon as possible. Now that I know this, I’m trying to update all my code.

OK but how to do that with a table? Because you can use declare to declare an empty array like this:

declare -a myarray

Well I found out that you can use local or declare to define an array.

Apparently either will set a local variable. Cool.

So this should work like the instruction above, right?

local -a myarray

But the difference, I think, is that declare defines the variable specifically as an array. Where as local imports the array into a variable but the variable is not specifically intended for…

Leave a comment