Created
September 30, 2017 13:54
-
-
Save mateuszalmannai/8bc8cff1e84318d82c11004f86057966 to your computer and use it in GitHub Desktop.
bash arrays, i.e. the closest thing to a map/hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
declare -A weapons=( | |
['Straight Sword']=75 | |
['Tainted Dagger']=54 | |
['Imperial Sword']=90 | |
['Edged Shuriken']=25 | |
) | |
# declare -A MYMAP=( [foo]=bar [baz]=quux [corge]=grault ) # Initialise all at once | |
# echo ${MYMAP[foo]} | |
echo "Keys: ${!weapons[@]}" # Print all keys - quoted, but quotes removed by echo | |
echo "" | |
echo "Looping through keys: " | |
for K in "${!weapons[@]}"; do echo $K; done # Loop through all keys in an associative array | |
echo "" | |
# Read entire array | |
echo "Array Values: ${weapons[@]}" | |
echo "" | |
echo "Looping through values:" | |
for V in "${weapons[@]}"; do echo $V; done # Loop through all values in an associative array | |
echo "" | |
echo "Looping through keys and values: " | |
for K in "${!weapons[@]}"; do echo $K --- ${weapons[$K]}; done # Looping through keys and values in an associative array | |
echo "" | |
print_array(){ | |
echo "Printing associative array passed to function as argument: " | |
local -n array=${1} | |
for i in "${!array[@]}"; do | |
printf "%s\t%d\n" "${i}" "${array[${i}]}" | |
done | |
} | |
echo "" | |
print_array weapons | |
echo "" | |
# Check if values exist in Associative Array | |
key_to_check_for='Edged Shuriken' | |
if [ "${weapons[${key_to_check_for}]}" ]; then | |
echo "Key '${key_to_check_for}' exists" | |
else | |
echo "Key '${key_to_check_for}' does not exist" | |
fi | |
# function to start java service with port name target-path | |
# function to start java service with port name and target-path in associative array | |
# start_all -> start_single arguments_array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment