I am using
GNU bash, version 4.3.11(1)-release-(x86_64-pc-linux-gnu)
I am using a asscoiative array to store values and I want to check, whether a key is contained within the array with set -u
included in the bash file.
The important part (you can find the script below) is where I want to get the value from the array like this ${backups[$service]}
What is not working:
set -u
it just exits with an error state and says line xx: backups[$service]: unbound variable
.${instances[$1]}
.What is working though:
set -u
it works.${!backups[*]}
works with set -u
${backups[@]}
works with set -u
This is my script:
#!/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
You could test using bash's parameter expansion to return a particular value if the given value doesn't exist:
if [ "${backups[$service]:-NOT_HERE}" != "NOT_HERE" ]; then
# do what you want if the value does exist in the array
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With