Sample Header Ad - 728x90

Bash/macOS: Getting a variable by its name, inside of a function

1 vote
3 answers
99 views
In Bash for macOS, I need to be able to pass a string to a function and return the value of a variable named after that string, as well as the string itself. Here's what I have so far, which doesn't work:
varTest="If you can read this, it worked"

function testFunction {
    echo "Variable name is $1"
    echo "Contents are $(${$1})"
}

testFunction varTest
> Variable name is varTest
> Contents are varTest
When actually the second line should say Contents are If you can read this, it worked. In PowerShell it'd be easy:
$varTest="If you can read this, it works"

function testEcho ($string) {
   write-host "Variable name is $string"
   (get-variable $string).value
}

testEcho varTest
> Variable name is varTest
> If you can read this, it works
Does bash have any equivalent to Get-Variable? This will be for Bash (not ZSH) on macOS devices (so v3.2.57).
Asked by seagull (111 rep)
Feb 3, 2025, 04:23 PM
Last activity: Feb 3, 2025, 06:05 PM