bashfunctionparameterspositional-parameter

Parameter is not visible in function


I am writing a script, where I need to work with parameters.

Here is my foo.sh:

say_hello()
{
  if [ "$1" == "hello" ]
  then
    echo "hello"
  else
    echo "<$1>"
  fi
}

echo "$1"
say_hello

The output looks very strange for me:

hello
<>

Could you explain me why in function I can`t work with params? And how I could pass script params in function?


Solution

  • Parameters you pass to functions in your shell are different from parameters passed to the shell itself.

    For example, if print_script_args looks like this:

    echo $1
    echo $2
    

    then ./print_script_args hello world will print this:

    hello
    world
    

    and if print_function_args looks like this:

    foo() {
        echo $1
        echo $2
    }
    
    foo bye world
    

    then ./print_function_args hello planet will print this:

    bye
    world
    

    — the parameters to the script do nothing, because what's printed is the parameters passed to the shell function, namely bye world.