BASH – The variable content of which refers to another variable

 

For example, there is the N number of variables, "var_1", "var_2" and so on, the script takes as arguments only the number of the variable, and its contents should be in the new var variable.

If you execute this script, passing it as argument "1":

./my_script.sh 1

 

my_script.sh

#!/bin/bash

var_1='MY_VAR_NUMBER_1'
var_2='MY_VAR_NUMBER_2'
var_3='MY_VAR_NUMBER_3'

var="var_$1"
echo $var

 

That script will return:

var_1

 

And we need the contents of the variable "var_1". To do this, the "echo" command should look like this:

echo "${!var}"

 

In this case, it will return:

MY_VAR_NUMBER_1

Tagged: Tags

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments