Create nameref for accessing variable from another bash – Code Example

Total
0
Shares

In this article we will show you a bash script code for creating nameref for accessing a variable from another variable. This is very useful as it creates a dynamic linking between the variable name and value of another variable.

Code Example –

1. Declaring nameref

#!/bin/bash

first_name="Akash"
first_pet="jackie (pup)"

field="name"

declare -n ref=first_$field

echo $ref

# Output:
# Akash

2. Naming variable based on another variable –

#!/bin/bash

first_name="Akash"
first_pet="jackie (pup)"

field="love"
declare "first_$field=mathematics"

echo $first_love

# Output:
# mathematics

Inspired from Dylan Araps

Live Demo

Open Live Demo