0

I'm trying to force the restart of my rsyslog server. I have sanitary reboot during the day, and sometimes the restart fails, so I want to restart it until the restart is a success.

At this point I'm trying to check if the output of the restart matches the output it is supposed to give when the restart is good.

But I don't understand why the if statement below doesn't work. It always goes to the else statement whether I put a == or != in the test condition.

Is there a way to check if a multi-line string is equal to another predefined multi-line string?

#!/bin/sh
endv=0
testv="Shutting down system logger: [  OK  ]
Starting system logger: [  OK  ]"
startv="$(/etc/init.d/rsyslog restart)"

while [ $endv == 0 ]; do
        echo "$startv"
            if [[ "$startv" != "$testv" ]]; then
               startv="$(/etc/init.d/rsyslog restart)"
                echo THEN
            else
                echo ELSE
                endv=1
            fi
done
4
  • AFAIK it should work... in bash - however /bin/sh is not bash on Ubuntu systems (and doesn't support the [[ ... ]] extended test). However I would avoid string tests if possible - doesn't the init script return an exit code? Apr 11, 2017 at 13:53
  • Also, are you sure rsyslog outputs to stdout?
    – choroba
    Apr 11, 2017 at 14:43
  • For the first question I'll have to check For the second, yes, when I check with echo "$startv" I get the result I'm expecting :
    – N.Lacroix
    Apr 11, 2017 at 14:58
  • [ a == b ] is also not standard, and dash doesn't support it. Use a single = for string comparison.
    – ilkkachu
    Apr 11, 2017 at 19:15

1 Answer 1

0

A few preliminaries:

  1. You should probably be moving away from invoking SysV init scripts directly; you are at least one and likely two steps behind the curve ( SysV init was replaced by upstart and then by systemd). For example:

    systemctl restart rsyslog.service
    
  2. Whichever init interface you use, it's likely that you can use the command's EXIT_STATUS directly rather than capturing its output and testing string equality. For example:

    systemctl restart rsyslog.service
    if [ $? -ne 0 ]; then
      ...
    fi
    

    (in any case, as @choroba poined out in comments, the '[OK]' message may in fact be going to standard error rather than standard output).

  3. In Ubuntu, /bin/sh is not bash: see DashAsBinSh. Among other things, that means it won't support the [[ . . . ]] extended test syntax.


Having got those out of the way, bash does indeed support string equality tests on multiline strings e.g.

$ str1='This is
a string'
$ str2='That is
a string'
$ str3='This is
a string'
$
$ [[ "$str1" != "$str1" ]] && echo "No match" || echo "Match"
Match
$ [[ "$str1" != "$str2" ]] && echo "No match" || echo "Match"
No match
$ [[ "$str1" != "$str3" ]] && echo "No match" || echo "Match"
Match

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .