0

I have a function in bash

foo ()
{
     # does some work
}

and I pass a parameter that contains a dot (for example hostnames contain dots)

HOSTNAME=`hostname` # pretend its host.on.a.net
foo $HOSTNAME

When foo does work on HOSTNAME, it will split into multiple arguments and $1 will be host instead of the full host.on.a.net

How do I avoid this default behavior?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
LeanMan
  • 474
  • 1
  • 4
  • 18
  • 3
    Double-quote the variable reference (`foo "$HOSTNAME"`). Also, it sounds like you changed `IFS`; if you do that, you should set it back to normal ASAP to avoid weird effects like this. Also, `HOSTNAME` is a standard pre-set variable. If you want its standard value, just use it; otherwise, use another name (preferably lower- or mixed-case, do avoid problems like this). BTW, [shellcheck](https://www.shellcheck.net) will spot many common mistakes like the quoting issue; I highly recommend it. – Gordon Davisson May 30 '21 at 04:42
  • I did change `IFS` within a script but isn't that bounded by the scope of the script? I also removed that code within the script. Anyways, I added the quotes and it solved the problem. My god...I can't believe it was all due to that... smh... – LeanMan May 30 '21 at 04:56
  • Not double-quoting vars and changing `IFS` are both kind of risky; doing both is almost certain to cause trouble. – Gordon Davisson May 30 '21 at 05:39
  • not double quoting is a convention? Bash should just do it by default if its risky behavior. IFS was part of another SO... oh well... – LeanMan May 30 '21 at 06:14
  • The original unix shell would word-split any unquoted variable references (and command substitutions and...) based on `IFS` because it seemed like a useful feature at time. Over the years it's become clear that this default is actually a bad idea, but most shells still maintain this behavior for compatibility (zsh is the exception). So... experienced shell scripters learn to double-quote, to avoid trouble. – Gordon Davisson May 30 '21 at 06:27
  • Thank you for the shellcheck website. I'm using it and the pointers are very useful. – LeanMan May 30 '21 at 06:50

0 Answers0