how.wtf

Dynamic variable names in Bash

· Thomas Taylor

In Bash, dynamic variables can be created using indirect expansion.

How to create a dynamic variable name

In a CI container, there may be a need to delineate between different environment variable values using a prefix for a variable name.

1#!/bin/sh
2# In the container at runtime:
3# export PROD_TOKEN="123"
4env="PROD"
5secret="${env}_TOKEN"
6echo ${!secret}

Output:

1123

In the example above, the secret value is PROD_TOKEN after expansion. Using indirect expansion, ${!secret} references 123.

#Bash  

Reply to this post by email ↪