Frage

#!/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 ?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top