2017-06-29 27 views
1

我使用獲取元素在bash與集-u

  • GNU bash, version 4.3.11(1)-release-(x86_64-pc-linux-gnu)

我使用的是asscoiative陣列存儲的值,我想檢查密鑰是否包含在陣列set -u包括在bash文件中。

的重要組成部分(你可以找到下面的腳本)是我想從這樣的${backups[$service]}

陣列獲取的價值有什麼不工作:

  • 當我執行腳本與set -u它只是退出一個錯誤狀態,並說line xx: backups[$service]: unbound variable
  • 它也不適用於${instances[$1]}

什麼是工作,但:

  • 沒有set -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 

回答

1

您可以測試使用bash's parameter expansion返回一個特定的值,如果給定值沒有按不存在:

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

真的很好,它按預期工作。我沒有看着那個方向謝謝。 – rocksteady

+0

現在起作用了,一定是拼寫錯了。爲了簡潔起見,我將刪除以前的評論。 TL; DR'$ set -u;聲明-A my_array;關鍵=丟失; my_array [exists] = value; [[-n「$ {my_array [$ key] - }」]] || echo Unset「會導致4.1,4.2和4.3的輸出」Unset「 –