0

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Laughing_Man
  • 179
  • 16

2 Answers2

2

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39
0

You need to call the say_hello function with an input parameter.

Within say_hello, $1 refers to the first argument that was passed to that function. You are calling it without any arguments though, like this:

say_hello

What you want is pass $1 (from the main script context) as a parameter to the say_hello function, like this:

say_hello $1

In the script, $1 refers to the first argument passed to the script when it was run from the command-line. In the function say_hello, $1 refers to the first argument that was passed to the function when it was called from the script.

Kaan
  • 5,434
  • 3
  • 19
  • 41