Den*_*son 27
在 Bash 4 中,您可以使用关联数组:
# set up array of constants
declare -A array
for constant in foo bar baz
do
array[$constant]=1
done
# test for existence
test1="bar"
test2="xyzzy"
if [[ ${array[$test1]} ]]; then echo "Exists"; fi # Exists
if [[ ${array[$test2]} ]]; then echo "Exists"; fi # doesn't
Run Code Online (Sandbox Code Playgroud)
要最初设置数组,您还可以进行直接分配:
array[foo]=1
array[bar]=1
# etc.
Run Code Online (Sandbox Code Playgroud)
或者这样:
array=([foo]=1 [bar]=1 [baz]=1)
Run Code Online (Sandbox Code Playgroud)
tok*_*and 10
这是一个老问题,但我认为最简单的解决方案还没有出现:test ${array[key]+_}
. 例子:
declare -A xs=([a]=1 [b]="")
test ${xs[a]+_} && echo "a is set"
test ${xs[b]+_} && echo "b is set"
test ${xs[c]+_} && echo "c is set"
Run Code Online (Sandbox Code Playgroud)
输出:
a is set
b is set
Run Code Online (Sandbox Code Playgroud)
要查看这项工作如何检查这个。
小智 5
有一种方法可以测试关联数组的元素是否存在(未设置),这与空不同:
isNotSet() {
if [[ ! ${!1} && ${!1-_} ]]
then
return 1
fi
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
declare -A assoc
KEY="key"
isNotSet assoc[${KEY}]
if [ $? -ne 0 ]
then
echo "${KEY} is not set."
fi
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
124060 次 |
最近记录: |