下面的循环中“+”的意义是什么for
:
for i in $*;do
if [[ ${array1[$i]+DEFINED} == 'DEFINED' ]];then
command1
fi
done
答案1
看https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion在手册中。
如果该变量有值,则替换为“DEFINED”一词,否则如果该变量未设置,则不替换任何内容。
$ unset foo; echo ">${foo+DEFINED}<"
><
$ foo=""; echo ">${foo+DEFINED}<"
>DEFINED<
$ foo=bar; echo ">${foo+DEFINED}<"
>DEFINED<
您的代码看起来像有一个关联数组array1
,并且您正在迭代位置参数以对某些数组值执行某些操作。
# set up the array
declare -A array1
array1[abc]=first
array1[def]=second
array1[ghi]=third
# set the positional parameters
set -- ghi abc
for i in "$@"; do
if [[ ${array1[$i]+DEFINED} == 'DEFINED' ]]; then
echo "found $i -> ${array1[$i]}"
fi
done
found ghi -> third
found abc -> first