deducing the name of the variable from positional parameters in a posix shell

StackOverflow https://stackoverflow.com/questions/22897056

  •  28-06-2023
  •  | 
  •  

Вопрос

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