我正在使用
GNU bash, version 4.3.11(1)-release-(x86_64-pc-linux-gnu)
我正在使用 asscoiative array 来存储值,我想检查一下键是否包含在数组中 set -u
< / strong>包含在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
答案 0 :(得分: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