Shamdor
Shamdor

Reputation: 3099

Function argument used but not passed

What happens if I define a bash (or any other shell) function that takes an argument, but don't pass an argument when make a call to it? Is an empty string guaranteed to be passed by default?

function test() {
  echo $1
}
test 

Upvotes: 1

Views: 488

Answers (2)

Tim
Tim

Reputation: 4958

In this case, $1 is unset. Unused positional parameters are unset by default, which is slightly different than being set to null. If you wrote foo="", then $foo would be null.

One of the differences is that referencing an unset parameter will result in an error if you have the nounset shell attribute set (set -o nounset).

For more information:

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158230

Check this http://tldp.org/LDP/abs/html/othertypesv.html#EX17

If a script expects a command-line parameter but is invoked without one, this may cause a null variable assignment, generally an undesirable result. One way to prevent this is to append an extra character to both sides of the assignment statement using the expected positional parameter.

Upvotes: 0

Related Questions