0

I am trying to compare two variables in a .sh file but it never works ;-(
How can I compare them?

curDate=2014-03-09
nextDate=2014-04-17

if [ “$nextDate” = “$curDate” ]; then
   echo $curDate = $nextDate
else
    echo $curDate != $nextDate
fi
4
  • 3
    The code works just as expected - for the case you provide it prints 2014-03-09 != 2014-04-17 and when I change the curDate to the same value as nextDate it prints: 2014-04-17 = 2014-04-1. Also on ideone: ideone.com/FSFMof and ideone.com/Qu59WJ Commented Sep 16, 2015 at 10:10
  • Are you actually using Bash, or some other shell? Do you have #!/bin/bash at the top of your script? Commented Sep 16, 2015 at 10:16
  • 3
    Are the fancy quotes and actually in your script? They should be normal double quotes ". Commented Sep 16, 2015 at 10:40
  • I am using the Mac OSX terminal and the code does not work. Commented Sep 16, 2015 at 11:13

2 Answers 2

1

Everything that is supposed to be a string should better be quoted:

echo "$curDate != $nextDate"

instead of

$curDate != $nextDate

Consider quoting date assignments too.

Try running this:

var=asd das
for thing in $var; do
echo $thing
done

and then with var="asd das"

Asides from that - use " instead of in if [ “$nextDate” = “$curDate” ]; then

Sign up to request clarification or add additional context in comments.

Comments

0

I found the solution. In Mac OSX this solution works:

#!/bin/bash
  a=2014-03-09
  b=2014-03-09
if [[ $a == $b ]] ; then
  echo Found.
else
  echo not found
fi

1 Comment

Your original code would work as well, if you used "..." instead of “...” to quote the parameter expansions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.