![该语句中“+”的意义是什么? if [[ ${array1[$i]+DEFINED} == 'DEFINED' ]]](https://linux22.com/image/11187/%E8%AF%A5%E8%AF%AD%E5%8F%A5%E4%B8%AD%E2%80%9C%2B%E2%80%9D%E7%9A%84%E6%84%8F%E4%B9%89%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F%20if%20%5B%5B%20%24%7Barray1%5B%24i%5D%2BDEFINED%7D%20%3D%3D%20'DEFINED'%20%5D%5D.png)
下面的循环中“+”的意义是什么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