Search code examples
bashzsh

Trailing whitespace in zsh commands


I am writing a zsh script that captures a hostname from file README and ensures that it exists on the network by pinging it. The following is my code:

HOSTNAME=$(cat README 2>/dev/null | grep -oP "^Host(name)*:[\s]+\K(.*)")
ping -w 5 -c 1 $HOSTNAME >/dev/null 2>&1
if [ $? != 0 ]; then
    # error
else
    # all good
fi

I noticed that if the line that contains the hostname in README has a trailing space, ping doesn't work. For example, the line could look like the following where I represent white space with an _ character.

Hostname:____bobscomputer_

Does zsh not get rid of extra whitespace in its commands like bash does?


Solution

  • You're thinking of word splitting of unquoted variables, which Bash does implicitly but Zsh doesn't. For example:

    $ cat test.sh
    var="foo bar"
    printf '%s\n' $var
    $ bash test.sh
    foo
    bar
    $ zsh test.sh
    foo bar
    

    If you wanted to do word splitting in Zsh, use $=var.

    BTW, here's an awk command that's simpler and avoids the problem (assuming hostnames can't contain whitespace):

    HOSTNAME=$(awk '/^Host(name)?:/ {print $2}' README)