0

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?

peachykeen
  • 4,143
  • 4
  • 30
  • 49

2 Answers2

1

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Your variable HOSTNAME has some whitespace on the tail end. One way to fix this is to strip leading/trailing whitespace from a parameter.

In this case, you could do so by adding a line above the ping command, shown below:

Before

# Original line
ping -w 5 -c 1 $HOSTNAME >/dev/null 2>&1

After

# Strip leading/trailing whitespace from $HOSTNAME
HOSTNAME=${(MS)HOSTNAME##[[:graph:]]*[[:graph:]]}

# Original line
ping -w 5 -c 1 $HOSTNAME >/dev/null 2>&1
chahu418
  • 327
  • 3
  • 8