I am trying to extract the value from a bash array. It works fine if it is the following code -
### stk3.sh
#!bin/bash
declare -x -A my_ids
my_ids[cat]=100
my_ids[dog]=200
id_key=${1:-cat} ## setting default
echo "Id key is :${id_key}"
id_no=${my_ids[$id_key]}
echo "Value is ### ${id_no}"
if I execute the above I get the desired output - (saved the above script in stk3.sh)
./stk3.sh dog
Id key is :dog
Value is ### 200
Now, when I use functions, I am unable to get the desired output. Defined the function in one script (stk1.sh) and calling the function to get the value from a specific key from another script (stk2.sh)
### stk1.sh
#!/bin/bash
declare -x -A my_ids
function my_ids {
my_ids[cat]=100
my_ids[dog]=200
echo "Length of Array :${#my_ids[*]}"
echo "*** Now printing the contents of the Array ...."
for x in "${!my_ids[@]}"
do
printf "$x ${my_ids[$x]} \n"
done
}
my_ids
function get-value {
printf "$1\n"
if [[ -n "$1" ]]
then
id_no=${my_ids[$id_key]}
fi
}
When calling the function using, I am NOT getting the desired results- Here is my stk2.sh
### stk2.sh
#!/bin/bash
source stk1.sh
id_key=${1:-cat} ## setting default
echo "Id key is :${id_key}"
id_no=$(get-value $id_key)
echo "Value is ### ${id_no}"
Output after executing skt2.sh, As you can see it is not returning the value of id _no, which in this case should be 200:
./stk2.sh dog
Length of Array :2
*** Now printing the contents of the Array ....
dog 200
cat 100
Id key is :dog
Value is ### dog