1

I'm trying to figure out how to get var names from arguments on a function.

I know to get the var name you can do it in many ways:

#!/usr/bin/env bash

foo="bar"

var_name=${!foo@}
echo $var_name" = "$foo

var_name=${-+foo}
echo $var_name" = "$foo

var_name=$'foo'
echo $var_name" = "$foo

var_name=$"foo"
echo $var_name" = "$foo

All of these examples produce the output foo = bar

Inside a function, the argument vars are "${1}", "${2}", etc. What I want is to take the var name before passing it as argument to a function from that function. Example:

#!/usr/bin/env bash

function sample() {
    echo ${!1@} #This produce en error: test.sh: line 4: ${!1@}: bad substitution
    echo ${-+1} #This produce "1" as output
    echo $'1' #This produce "1" as output
    echo $"1" #This produce "1" as output
}

foo="bar"
sample "${foo}"

Expected output is "foo". How can achieve this?

OscarAkaElvis
  • 5,384
  • 4
  • 27
  • 51
  • 1
    You can't achieve this: when the shell reads `sample "${foo}"`, it first expands the variable `$foo` (and hence forgets that it comes from the variable `foo`), and then calls the function `sample` with the expansion obtained. You probably want _indirect expansion_ instead: call `sample foo` and write your function as `sample() { echo "${!1}"; }`. But please be aware that most of the time, when people use this, it's because of bad design: either redesign your code or use another language! – gniourf_gniourf Dec 25 '17 at 11:40
  • And by the way, you're very likely wrong on what all of the expansions you showed do! `${!foo@}` will expand to all the variables that start with `foo`. Try it: `foo1=hello foo2=world; echo "${!foo@}"`. `${-+foo}` is a weird way of saying: _if `-` is unset, then expand to `foo`_. Very likely `-` is set (since it's a special variable), so it will expand to `foo`. `$'foo'` is just an [ANSI-C quoting](https://www.gnu.org/software/bash/manual/bashref.html#ANSI_002dC-Quoting) and `$"foo"` is for [locale-specific strings](https://www.gnu.org/software/bash/manual/bashref.html#Locale-Translation). – gniourf_gniourf Dec 25 '17 at 11:47
  • Thank you. I'll try to redefine structure. Very helpful. Put it as an answer to accept it. – OscarAkaElvis Dec 25 '17 at 11:50

0 Answers0