문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top