Search code examples
arraysbashdefault-value

Bash Array value in default value assignment


I'm trying to assign an array of three values to a variable if it hasn't been assigned yet with the line

: ${SEAFILE_MYSQL_DB_NAMES:=(ccnet-db seafile-db seahub-db)}

Unfortunately, echoing ${SEAFILE_MYSQL_DB_NAMES[@]} results in (ccnet-db seafile-db seahub-db) and ${SEAFILE_MYSQL_DB_NAMES[2]} prints nothing. It seems, the value has been interpreted as a string and not as an array. Is there any way I can make my script assign an array this way?


Solution

  • How about doing it in several stages? First declare the fallback array, then check if SEAFILE_MYSQL_DB_NAMES is set, and assign if needed.

    DBS=(ccnet-db seafile-db seahub-db)
    [[ -v SEAFILE_MYSQL_DB_NAMES ]] || read -ra SEAFILE_MYSQL_DB_NAMES <<< ${DBS[@]}
    

    Based on this answer.