Defining and Manipulating Key-Value Arrays
Defining Key-Value Arrays
To define a key-value array in Bash, you can use the declare
command with the -A
option:
declare -A my_array
This creates an associative array named my_array
.
You can then add key-value pairs to the array using the following syntax:
my_array["key1"]="value1"
my_array["key2"]="value2"
my_array["key3"]="value3"
Accessing and Manipulating Key-Value Arrays
To access the value of a specific key, use the key as an index:
echo ${my_array["key1"]} ## Output: value1
You can also iterate over the keys and values of the array using a for
loop:
for key in "${!my_array[@]}"; do
echo "Key: $key, Value: ${my_array[$key]}"
done
This will output:
Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3
To add or modify a key-value pair, use the same syntax as when defining the array:
my_array["key4"]="value4"
my_array["key2"]="new_value2"
To remove a key-value pair, you can use the unset
command:
unset 'my_array[key3]'
Associative Array Operations
Bash key-value arrays support various operations, such as:
- Checking if a key exists:
if [[ -v my_array["key1"] ]]; then ... fi
- Getting the number of key-value pairs:
echo ${#my_array[@]}
- Getting a list of all keys:
echo "${!my_array[@]}"
By understanding how to define, access, and manipulate key-value arrays in Bash, you can leverage this powerful data structure to write more efficient and organized shell scripts.