Skip to content

Instantly share code, notes, and snippets.

@scop
Created December 1, 2025 11:29
Show Gist options
  • Select an option

  • Save scop/210266a4351ecdb34ce7f2b6efb31750 to your computer and use it in GitHub Desktop.

Select an option

Save scop/210266a4351ecdb34ce7f2b6efb31750 to your computer and use it in GitHub Desktop.
`PROMPT_COMMAND` array in bash >= 5.1

Since bash 5.1, PROMPT_COMMAND can be an array. That's nice, as it's easier to robustly operate on an array on per element basis than on a delimited string to that effect.

Adding

Things that add to the variable can coexist and just operate on it as they would normally do, whether they treat it as an array or a scalar, without doing extraneous checks.

The first gotcha related to this is that operating on an array variable as if it was a scalar operates on the array's first element.

The second is that adding array elements to something that was introduced as a scalar magically "makes the variable an array". For example: foo=bar; foo+=(quux) # foo is now a 2-element array

Removing

Removing is trickier. Luckily it's also not as often needed as adding.

If something prepended elements to the variable as an array, things that operate on it as a scalar would no longer find what they're looking for as they only access the array's first element. Adding elements by appending rather than prepending avoids this (and looks cleaner anyway).

If something modifies the first element of the array variable array (in this context, something treating it as a scalar), things that operate on it as an array may no longer find their additions as-is in that element, i.e. they can't just simply search for exact matches and unset[i] their findings. Instead, they need need to look for their data not only as they added it as the whole content of a new array element, but also in each element's content treating it as a semicolon separated string of "sub-elements".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment