[Code Example] Create nameref for accessing variable from another bash

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

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like