i've been looking around for this all over, but either i don't know how to ask the question correctly, or it's not a common enough issue...
In PHP this is (almost) trivial:
function getSite(string $prefix = 'prod') {
$DEV_SITE='dev.site.com';
$PROD_SITE='www.site.com';
$site = strtoupper("{$prefix}_site");
return ${$site};
}
getSite(); // www.site.com
getSite('dev'); // dev.site.com
i'll try to build up to it incrementally.
i have a set of variables with _SITE
suffix.
DEV_SITE=dev.site.com
PROD_SITE=www.site.com
i want to call a script with JUST the prefix as an argument and default to PROD.
#!/bin/bash
PREFIX=${1:-PROD}
echo $PREFIX
$ script.sh dev
dev
$ script.sh
PROD
i want to append "_SITE"
to $PREFIX
to get one of my variable names:
VAR_NAME="${1:-PROD}_SITE"
echo $VAR_NAME
---
$ script.sh dev
dev_SITE
$script.sh
PROD_SITE
Awww, dev_SITE
isn't valid, but i don't want the caller to need to know the difference.
So let's make the argument "case-insensitive" so dev
will convert to match a variable name:
SITE="${1:-PROD}_SITE"
# This does NOT work:
SITE="${1:-PROD^^}_SITE"
echo ${SITE^^}
---
$ script.sh dev
DEV_SITE
$script.sh
PROD_SITE
Great. But what's the simplest way to get the value of that name?
Everything i've tried with ${SITE^^}
gives me "bad substitution" errors.
echo ${$SITE^^}_PROD
echo ${${!SITE^^}_PROD}
echo ${"${SITE^^}_PROD"}
echo ${"${!SITE^^}_PROD"}
and so on...
If i assign and reassign, it'll work:
SITE="${1:-PROD}_SITE"
SITE=${!SITE^^}
echo $SITE
---
$ script.sh dev
dev.site.com
$ script.sh
prod.site.com
i believe it has something to do with all substitutions being done in a single step, but i've also tried subshells and piping the name into other commands, but can't get my head around it.