Programming, robotics, traveling

04 Jan 2022

Bash: Parameter Expansion to do a nested array

Main idea how to make nested array in Shell is use a separator for example ::.

But the trick is in using Parameter Expansion for split elements.

Parameter Expansion is the term that refers to any operation that causes a parameter to be expanded (replaced by content). In its most basic appearance, the expansion of a parameter is achieved by prefixing that parameter with a $ sign.

#!/bin/sh

HOSTS=(
    'example-1.com::9000'
    'example-2.com::9090'
)

for i in "${HOSTS[@]}"; do
    echo "a=${i%%::*} c=${i##*::}";
done
  • ${i%%::*} – deletes all symbols since :: to right direction
  • ${i##*::} – deletes all symbols since :: to left direction, but starts from the end

Unfortunately in Shell or Bash you cannot put string instead parametr, but in Zsh you can do that.

#!/bin/zsh

HOSTS=(
    'example-1.com::9000::/api'
    'example-2.com::9090::/metrics'
)

for i in "${HOSTS[@]}"; do
    echo "a=${i%%::*} b=${${i%::*}#*::} c=${i##*::}";
done

Where ${${i%::*}#*::} consists from ${i%::*} and ${<STR>#*::}

  • ${i%::*} – deletes symbols from :: to right direction (but since the last match)
  • ${<STR>#*::} – deletes symbols since :: to left direction, but starts from the end (but since the last match)

Source links: