I have a few environment variables. There are multiple such values I want to convert dynamically.
Env variable: I'm getting this env variable using printenv | grep proj_env_repo
( doing like printenv | grep $value
).
so the value is proj_env_repo
and my results are
proj_env_repo_db_username=username
I want to convert it to TF_ENV_db_username=username
Can someone help me with it? I'm looking for a function in bash script.
Best Answer
Using variable name prefix matching and variable indirection in
bash
:The loop uses
"${!proj_env_repo@}"
to generate a list of variable names that share the name prefixproj_env_repo
. In each iteration$variable
will be the name of one of these variables.Inside the loop,
export
is used to create a new environment variable by stripping off theproj_env_repo
prefix and replacing it with the stringTF_ENV
. The value for the new environment variable is had using the variable indirection${!variable}
, i.e. the value of the variable whose name is stored in$variable
.To additionally unset the original variable, use
unset "$variable"
afterexport
, before the end of the loop.Test running this with tracing turned on:
As a function taking the old name prefix as its 1st argument and the new prefix as its 2nd argument:
We resort to using
eval
over the loop here sincebash
does not support the syntax${!$1@}
. The function constructs the appropriate shell code (as a string) for renaming the variables according to the values of$1
and$2
(the 1st and 2nd argument given to the function), and then useseval
to execute this shell code.You would use this function as
... or, using variables,
Note: When doing things like these (using
eval
on user input), you must test that the code that you evaluate is valid and that it is what you expect it to be. In this case this mean validating$1
and$2
as valid variable name prefixes. Otherwise at least quotes and}
will cause syntax errors in theeval
, and there is a possibility of command injection.Note: This is the first time (I think) that I've ever had to use
eval
. I would never put myself in the position of having to use the above code though, but I don't know the background story to the question, obviously, so that's not real criticism of the question (which is an interesting one in itself).Related (on the Software Engineering site):