Default value
See Parameter Expansion in bash man page:
man -Pless\ +/parameter:-word bash
${parameter:-word}
Use Default Values. If parameter is unset or null, the expan‐
sion of word is substituted. Otherwise, the value of parameter
is substituted.
So
#!/bin/bash
array=("foo" "foo" "bar" "something else" "also something else" "bar")
declare -A map
map["foo"]="1"
map["bar"]="2"
for key in "${array[@]}";do
printf '%-20s -> %s\n' "$key" "${map["$key"]:-?}"
done
Will produce:
foo -> 1
foo -> 1
bar -> 2
something else -> ?
also something else -> ?
bar -> 2
Default to another variable
But, if you really want to use map[unknown], you could:
#!/bin/bash
array=("foo" "foo" "bar" "something else" "also something else" "bar")
declare -A map="( ["foo"]="1" ["bar"]="2" ["unknown"]="?" )"
for key in "${array[@]}";do
printf '%-20s -> %s\n' "$key" "${map["$key"]:-${map["unknown"]}}"
done
This will produce same output!
Note: you could even use "default to variable, with default":
echo "${map["$key"]:-${map["unknown"]:-?}}"
This will print
- content of
map["$key"], or if not exist,
- content of
map["unknown"], or if not exist,
- a single interrogation mark:
?.
You could map your array, using printf
array=("foo" "foo" "bar" "something else" "also something else" "bar")
declare -A map="( ["foo"]="1" ["bar"]="2" ["unknown"]="?" )"
printf -v mapStr '"${map["%s"]:-${map["unknown"]}}" ' "${array[@]}"
declare -a "mappedArray=($mapStr)"
echo "${mappedArray[*]@Q}"
'1' '1' '2' '?' '?' '2'
Then
printf -v mapStr '%-20s -> %%s\n' "${array[@]}"
printf "$mapStr" "${mappedArray[@]}"
foo -> 1
foo -> 1
bar -> 2
something else -> ?
also something else -> ?
bar -> 2
But using this way could lead to security issues!
See Warning: limitation at end of Array elements in sed operation
KEYis set tofooandmap["foo"]=""then what shouldecho ${map[$KEY]}output - a) an empty string or b) the character??