1

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 
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Shamdor
  • 3,019
  • 5
  • 22
  • 25

2 Answers2

2

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:

Community
  • 1
  • 1
Tim
  • 4,790
  • 4
  • 33
  • 41
0

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Hihi :) I never had to deal with more than 9 arguments in bash. I edited it to `${N}` for short, but then I found the above statement in the docs. Seems to be the correct answer to your question. – hek2mgl Apr 14 '15 at 00:32
  • The answer is yes the same way that using any other unassigned variable expands to the empty string. That statement is discussing a specific "error" that can occur for a missing argument and is a particularly poor "solution" for the problem (the final "However" note is much better). – Etan Reisner Apr 14 '15 at 00:41
  • @EtanReisner You are right. I can't delete this answer at the moment since it is accepted- – hek2mgl Apr 14 '15 at 00:45
  • 1
    I haven't seen that "Advanced" guide in years. :-) Note that it misses on a number of "best practices", like quoting your variables and validating your input. These days, usage like `[ -n "${N}" ]` is considered safe, at least in bash. And because `[` and `[[` are bash builtins, behaviour should be consistent and portable. – ghoti Apr 14 '15 at 00:45