WxPilot
WxPilot

Reputation: 133

BASH String Comparison Returning True

I'm trying to compare two timestamp variables to determine whether they are the same. The variable tempDate is used to hold the value of the last valid date, while the variable timeStamp will hold the value of the next timestamp in the loop.

I am using an if statement to detect if the two variables are not equal to each other, but the if statement returns true every time. The variables are assigned like so:

timeStamp=${col2:5:2}${col2:8:2}${col2:0:4}
tempDate=${col2:5:2}${col2:8:2}${col2:0:4}

# Here is how the if statement is written...
if [ "$timestamp" != "$tempDate" ]; then
     #Additional Code
     echo "It is a new day!"
fi

Where col2 would equal an arbitrary timestamp assigned as:

col2=2010-01-01 00:54

When I execute my script the if statement returns true consistently, even when the two variables are visibly identical. Is this an issue with how my variables are assigned? or is it a simple syntax mistake?

Upvotes: 0

Views: 397

Answers (2)

mkj
mkj

Reputation: 2831

To avoid these kind of bugs caused by undefined variables add this in your script:

set -u

or you can add the option in the shebang line at the start of the script

#!/bin/bash -u

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362117

if [ "$timestamp" != "$tempDate" ]; then

should be

if [ "$timeStamp" != "$tempDate" ]; then

Note the capital "S".

Upvotes: 0

Related Questions