1
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
真的很好,它按預期工作。我沒有看着那個方向謝謝。 – rocksteady
現在起作用了,一定是拼寫錯了。爲了簡潔起見,我將刪除以前的評論。 TL; DR'$ set -u;聲明-A my_array;關鍵=丟失; my_array [exists] = value; [[-n「$ {my_array [$ key] - }」]] || echo Unset「會導致4.1,4.2和4.3的輸出」Unset「 –