Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an element from a associative array in bash with set -u

Tags:

arrays

linux

bash

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:

  • When I execute the script with set -u it just exits with an error state and says line xx: backups[$service]: unbound variable.
  • It also does not work for ${instances[$1]}.

What is working though:

  • Without 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
like image 938
rocksteady Avatar asked Sep 19 '25 01:09

rocksteady


1 Answers

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
like image 91
Eric Renouf Avatar answered Sep 20 '25 15:09

Eric Renouf