0

I'm new to bash scripting and i want to compare two strings, here's my code

#!/bin/bash
EXITCODE=0;
COMPARE_RESULT=sudo php /home/xxx/compareMD5.php
echo $COMPARE_RESULT
if [ "$COMPARE_RESULT"="ok" ]; then
    echo error log is not changed
    EXITCODE=10
elif [ "${COMPARE_RESULT}"="mysqlerror" ]; then
    echo mysqlerror
    EXITCODE=11
elif [ "${COMPARE_RESULT}"="apacheerror" ]; then
    echo apacheerror
    EXITCODE=12
fi
exit $EXITCODE

the php file will return either ok, mysqlerror or apacheerror and when i run the script, the COMPARE_RESULT prints "mysqlerror" but still goes in to if first if condition and print "error log is not changed", anyone know why? thanks

user2810081
  • 589
  • 1
  • 8
  • 27
  • Rocket has the problem solved, but I did want to point out the inconsistency in your code. you use $COMPARE_RESULT and later ${COMPARE_RESULT}. – gview Sep 10 '15 at 19:23
  • 1
    http://shellcheck.net is your friend. – Etan Reisner Sep 10 '15 at 19:28
  • It is a good idea to compare strings using the construct `[ "x${COMPARE_RESULT}" = "xok"` to avoid trouble when `COMPARE_RESULT` is empty. See [this](http://stackoverflow.com/q/174119/5128464). – vlp Sep 10 '15 at 19:42

1 Answers1

2
COMPARE_RESULT=sudo php /home/xxx/compareMD5.php

This will not do what you think. You need to enclose the command in backticks so that it runs and COMPARE_RESULT will be set to its output.

COMPARE_RESULT=`sudo php /home/xxx/compareMD5.php`
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    In bourne and bash '=' does work for string equality. Otherwise, I would tend to agree with your comment as the likely cause of the problem. – gview Sep 10 '15 at 19:17
  • 1
    In most cases, yeah '==' is a problem, and certainly that's true for a php developer, but not the issue in his code. However, you pinpointed the issue, he's not actually storing the return value in his variable. Because he saw output from the command line program running, he assumed it was working. – gview Sep 10 '15 at 19:21
  • @gview: Yeah, I forgot about how bash works, haven't used shell scripts in a while :-) – gen_Eric Sep 10 '15 at 19:22
  • 1
    Secondary issue is that without spaces around `=` in the tests they aren't actually testing what he expects. – Etan Reisner Sep 10 '15 at 19:27
  • 1
    Or enclose it like this `$(sudo php /home/xxx/compareMD5.php)` – Fernando Martín Besteiro Sep 10 '15 at 19:28