Explaining Arrays as Argument Lists in Bash

Pavol Kutaj
1 min readMar 16, 2024

--

The aim of this page📝 is to explain a major function of index array in Bash — to build a list of flags/arguments. In other words, when arrays are used to define flags calling a binary from a Bash script. My take is based on the example from the Google bash style guide.

  • Style Guide’s section on arrays opens with

Bash arrays should be used to store lists of elements, to avoid quoting complications. This particularly applies to argument lists

— https://google.github.io/styleguide/shellguide.html#arrays

  • Googlers provide an example — which they do not justify enough for me.
declare -a flags
flags=(--foo --bar='baz')
flags+=(--greeting="Hello ${name}")
mybinary "${flags[@]}"
  • Why not to pass flags directly? …Something I do all the time. For that example, I’d try to do
mybinary --foo --bar="baz" --greeting="Hello ${name}"

Reasons

  • Using arrays can keep flags dry (don’t repeat yourself) — if you call the binary many times.
  • Arrays allow for dynamic construction of flag lists based on conditions.
  • → you may not know in advance what flags you are passing
  • Appending flags to an array allows for easy extension of the flag list.
  • Arrays help in avoiding word splitting issues that may occur when passing flags directly.
  • However, directly passing flags as arguments can work for simple cases with known flags
  • Arrays are recommended for complex scripts or scenarios with evolving flag requirements.

LINKS

--

--

Pavol Kutaj
Pavol Kutaj

Written by Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com

No responses yet