Arrays 使用set-u从bash中的关联数组中获取元素

Arrays 使用set-u从bash中的关联数组中获取元素,arrays,linux,bash,Arrays,Linux,Bash,我正在使用 GNUBash,版本4.3.11(1)-发布-(x86_64-pc-linux-GNU) 我正在使用一个关联数组来存储值,我想检查键是否包含在包含在bash文件中的set-u的数组中 重要的部分(您可以在下面的脚本中找到)是我希望从数组中获取值的位置,如下面的${backups[$service]} 什么不起作用: 当我使用set-u执行脚本时,它只是以错误状态退出,并显示第xx行:backups[$service]:unbound variable 它也不适用于${inst

我正在使用

  • GNUBash,版本4.3.11(1)-发布-(x86_64-pc-linux-GNU)

我正在使用一个关联数组来存储值,我想检查键是否包含在包含在bash文件中的
set-u的数组中

重要的部分(您可以在下面的脚本中找到)是我希望从数组中获取值的位置,如下面的
${backups[$service]}

什么不起作用:

  • 当我使用
    set-u
    执行脚本时,它只是以错误状态退出,并显示
    第xx行:backups[$service]:unbound variable
  • 它也不适用于
    ${instances[$1]}
但什么在起作用:

  • 不使用
    设置-u
    它可以工作
  • ${!backups[*]}
    set-u一起使用
  • ${backups[@]}
    set-u一起使用

这是我的剧本:

#!/bin/bash

set -euo pipefail

# all the services
services=(
  "service_without_backup"
  "service_that_needs_backup"
)

my_service="service_that_needs_backup"

# all the services that need a backup
declare -A backups
for service in $my_service
do
  backups[$service]=1
done

...
some other code
... 

# loop over all the services    
for service in ${services[@]}
do

  ...
  do something common to all services
  ...

  # backup services when defined to
  if [ ${backups[$service]} ]; then
    echo "    copy backup file"        
  fi
done
如果给定值不存在,可以使用测试返回特定值:

if [ "${backups[$service]:-NOT_HERE}" != "NOT_HERE" ]; then
    # do what you want if the value does exist in the array
fi

真的很好,它按预期工作。我没有朝那个方向看,谢谢。现在可以了,一定是拼错了什么。为了简洁起见,我将删除以前的评论。TL;DR
$set-u;声明-A my_数组;密钥=丢失;my_数组[存在]=值;[[-n“${my_array[$key]-}”]| | echo Unset
在4.1、4.2和4.3上产生输出
Unset