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

3
  • 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}. Commented Sep 10, 2015 at 19:23
  • 1
    shellcheck.net is your friend. Commented Sep 10, 2015 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. Commented Sep 10, 2015 at 19:42

1 Answer 1

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`
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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: Yeah, I forgot about how bash works, haven't used shell scripts in a while :-)
Secondary issue is that without spaces around = in the tests they aren't actually testing what he expects.
Or enclose it like this $(sudo php /home/xxx/compareMD5.php)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.