1

So this is my first function:

#!/bin/bash

lets_print () {

    echo hello $1
}

lets_print Earth

lets_print Mars

ready to show result

user@bash$ ./demo.sh

Hello Earth

Hello Mars

And this is my 2nd function:

#!/bin/bash

lets_print () {

    echo hello $1 $2
}

lets_print Earth

lets_print Mars

ready to show the second result:

user@bash$ ./demo.sh

Hello Earth

Hello Mars

Can someone please explain why they have the same result?

Right now I am thinking $1=Earth and $2=Mars. But I know this is wrong.

jesse_b
  • 37,005
Denny
  • 241

1 Answers1

4

They are showing the same result because you are only passing one positional parameter per function call. In order for mars to be the second parameter you would need to call like this:

lets_print Earth Mars

Recommended reading on positional parameters: 3.4.1 Positional Parameters

jesse_b
  • 37,005
  • @Denny If this solves your issue, please consider accepting the answer. – Kusalananda Apr 14 '18 at 07:20
  • Also, https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells and https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters and https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – Kusalananda Apr 14 '18 at 07:21