Question

#!/bin/sh
foo()
{
  printf "$1"
}
RANDOM_VAR="hello\n"
foo $RANDOM_VAR

When you pass 1 or more variables to a function, in this case foo, they are accessible through $1 $2 and so on; how do you go a step back from inside foo and print the name of the original variable which in this case means RANDOM_VAR ?

Était-ce utile?

La solution

Succinctly, you don't or can't tell from inside the function which variables were used to create the argument to the function. There's no guarantee that the argument is a variable, or a single variable — for example:

foo 123
foo ${HOME}:${PATH}

Further, if the function cares, it is probably mis-written. It should be as nearly self-contained as possible, and therefore independent of such issues. If it isn't, it suggests that maybe the function is not functionally cohesive.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top