noober
noober

Reputation: 1505

bash - how to dump all elements in array within usage

I'd like to dump my array to the user so they can see what the mappings would look like. I tried so with this statement printf '%s\n' "${cluster_to_endpoint[@]}" I'm trying to dump it within my usage function below, however I'm not getting the output i'm expecting.

Code in progress:

#!/bin/bash

set -e

usage () {
    echo "Usage: $0 -o oldcluster -n newcluster"
    printf '%s\n' "${cluster_to_endpoint[@]}"
}

while getopts ":o:n:" opt; do
  case $opt in
    o) old="$OPTARG";;
    n) new="$OPTARG";;
    *) usage
       exit 1
       ;;
  esac
done


# Mapping
declare -A cluster_to_endpoint=(
        [c1]=foobar2-01.us-east-1.my.com
        [c2]=foobar2-02.us-east-1.my.com
        [c3]=foobar2-03.us-east-1.my.com
        [c4]=foobar2-04.us-east-1.my.com)

# Echo info
echo "Source cluster:${cluster_to_endpoint[$old]}"
echo "Target cluster:${cluster_to_endpoint[$new]}"

Output:

-bash-4.1$ ./tst.sh -h
Usage: ./tst.sh -o oldcluster -n newcluster

Expecting:

Usage: ./tst.sh -o oldcluster -n newcluster

    [c1]=foobar2-01.us-east-1.my.com
    [c2]=foobar2-02.us-east-1.my.com
    [c3]=foobar2-03.us-east-1.my.com
    [c4]=foobar2-04.us-east-1.my.com

Upvotes: 0

Views: 357

Answers (2)

Kusalananda
Kusalananda

Reputation: 15633

You are calling your usage shell function before initializing the array cluster_to_endpoint.

Move the declare statement to before handling the command line.

In addition to that, the subscripts in an array must evaluate to integer values, and can't therefore be c1 etc. as you have. EDIT Apparently this is how you do associative arrays in Bash version 4+. Older Bash needs to use ordinary arrays (declare -a) with integer subscripts.

Upvotes: 1

Webert Lima
Webert Lima

Reputation: 14035

The code is executed from top to bottom, and when it enters the while loop, calls usage, which tries to print your array but it has not yet been initialized.

Put the declare statement before any access to it.

Upvotes: 3

Related Questions