How to Create dynamic variable names in Bash?

Dynamic variable names in Bash

In Bash, dynamic variable names can be created using curly braces {} and the exclamation mark ! operator.

Let's say you have a variable called fruit with a value of apple, and you want to create a new variable with a dynamic name that includes the value of fruit. You can do it like this:

name_of_${fruit}=Jonny   # This will create a new variable called name_of_apple with the value Jonny
echo $name_of_apple      # Output: Jonny

Here, the curly braces are used to specify the variable name, and the exclamation mark ! is used to evaluate the value of the variable.

You can also use dynamic variable names in arrays. For example:

echo ${count_of_apple}   # Output: 5

# You can also use dynamic variable names in arrays
fruits=(apple banana cherry)
for fruit in ${fruits[@]}; do
  echo ${count_of_${fruit}}   # Output: 5

Here, a dynamic variable name is created for each element in the fruits array. This allows you to create and manipulate variables based on dynamic values in Bash.

  1. How to parse command line arguments in Bash?
  2. Bash and shell script variable capitalization?
  3. How to get the directory where a Bash script is located from within the script itself?
  4. Parsing JSON with Unix tools
  5. Command not found error in Bash variable assignment
  6. How to set a variable to the output of a command in Bash?
  7. How to run Bash commands in Python?
  8. Extract filename and extension in Bash?
  9. Looping through the content of a file in Bash