how to differentiate between function arguments and script arguments

Viewed 1494

lets say I have a script called hello

$ cat hello
function1 () {
echo $1
}
function1 what
echo $1

and I call

$ sh hello chicken
what
chicken

How do i refer to the script parameters (chicken) inside the function. Would I have to rename all the script arguments or store them somewhere else? Whats the best way to handle this?

1 Answers

This is a case of shadowing, you can find information about it below https://www.gnu.org/software/bash/manual/html_node/Shell-Functions.html

If you try to picture it, the inner scope variable casts a "shadow" over the outer scope variable and hides it from view. As soon as the inner scope variable is gone, the program can again "find" the outer scope variable.

It's pretty much another variation of a general rule in programming where things that are more specific or refer to an inner scope, override things that are more generic or part of an outer scope.

If you wrote

temp="hi"
phrase(){
    echo "$temp"
    temp="hello"
    echo "$temp"
}
phrase

The result would be

hi
hello

because the variable of the inner scope "overshadows" the variable of the outer scope.

That can be prevented by storing your script's $1 parameter using another name. So, as you said, the best approach is to make sure all variables have different names by storing your script parameters inside distinctly named variables.

temp=$1
function1 () {
  echo "$1"
  echo "$temp"
}
function1 what
echo "$1"

Edit: I forgot to account for the fact that script variables are not available directly inside functions like @gordondavisson said, so even if you weren't passing the word "what" as a parameter to your function, you still wouldn't be able to print the word "chicken". So, in this case, the only possible way to use the parameter inside the function would be to assign $1 to a variable.

Related