2

I have below code.The logic here is if HostList conatains any blanck entry it should set class as blank, else it should be red.Now I am getting error-

test.sh[3]: syntax error at line 7 : `then' unexpected

can any one help me out?Thanks!!

     #! /bin/bash
file=./HostList.txt
{
  echo "<table>"
  printf "<tr>"
  if[%s -eq =""]; then
      class="blank"
  else
    class="red"
  fi    
    "<td" $class">%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    <td>%s</td>
    </tr>\n" $(cat "$file"|cut -d'.' -f1)
  echo "</table>"
}  > table.html


exit 0
Community
  • 1
  • 1
Monojit
  • 195
  • 2
  • 3
  • 14

3 Answers3

9

Bash is very sensitive about whitespace. This should work:

if [ "%s" = "" ]; then

Note that = is used for string comparison and -eq is used for integers.

edit:

More precisely, bash splits your original code like this:

if[%s # supposedly a command
-eq # parameter
=""] # parameter
; # end of command
then # keyword

At this point, Bash realizes that there is an unmatchen then keyword, and doesn't even try to run if[%s (which would fail too).

user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • 1
    @grails_enthu, this is because `[` is actually a command, so it needs to be space-separated from the `if` keyword and the following arguments. You need spaces around the `=` operator because the `[` command first considers the number of arguments it has been given before deciding what to do. See the bash manual: http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins and scroll down to the `test` command. – glenn jackman Mar 29 '12 at 13:58
3

I'm not sure what all that HTML markup is doing in there but the if statement should be something like:

if [[ $something == "" ]] ; then
    # do something
fi

In other words, you need some spaces between the brackets and the arguments, at a bare minimum.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

First, your if statement needs some spacing, and the -eq is unnecessary:

if [ %s = "" ]; then
    class="blank"
else
    class="red"
fi

But more importantly, %s is not a variable, so you can't compare it to anything (or as pointed out in the comments, not usefully). It's just a placeholder for the printf command. You're going to have to be a little more explicit:

hosts=($(cat "$file"))
echo "<table>"
echo "<tr>"
for host in ${hosts[@]}; do
    host=$(echo $host | cut -d'.' -f1)
    if [ "$host" = "" ]; then
        echo "<td class='blank'>"
    else
        echo "<td class='red'>"
    fi
done
echo "</tr>\n"
echo "</table>"

(The preceding has been minimally tested.)

chepner
  • 497,756
  • 71
  • 530
  • 681