snowexcuse
snowexcuse

Reputation: 3

if statement always true regardless of conditional operator

#!/bin/bash
WATCHDIR="/path/to/my/dir"
OKTIME="7200"
RESULTFILE="/path/to/some/file.tmp"
DONOTHING="$(printf 'good' > $RESULTFILE)"
SENDMAIL="$(printf 'bad' > $RESULTFILE)"
ELAPSEDTIME="$(expr $(date +%s) - $(stat -c %Y $WATCHDIR))"

if [ "$ELAPSEDTIME" -ge "$OKTIME" ]; then
     $SENDMAIL
else
     $DONOTHING
fi

I've been staring at this for too long, I've done multiple revisions, output the variable to separate files to check they are working, and lots of research on conditional statements in Bash today. For some reason the script always executes SENDMAIL even when I've manually verified that ELAPSEDTIME is less than OKTIME.

Upvotes: 0

Views: 150

Answers (2)

that other guy
that other guy

Reputation: 123680

"$(printf 'good' > $RESULTFILE)" executes the command in $() and replaces it with the output.

This means that you always execute:

printf 'good' > $RESULTFILE
printf 'bad' > $RESULTFILE

before you reach the if statement.

Please just avoid putting commands in variables. If you want a function, use a function:

#!/bin/bash
WATCHDIR="/mnt/remote/ian/test"
OKTIME="7200"
RESULTFILE="/mnt/remote/ian/result.tmp"
ELAPSEDTIME="$(expr $(date +%s) - $(stat -c %Y $WATCHDIR))"

donothing() { 
  printf 'good' > $RESULTFILE
}

sendmail() { 
  printf 'bad' > $RESULTFILE
}

if [ "$ELAPSEDTIME" -ge "$OKTIME" ]; then
     sendmail
else
     donothing
fi

Upvotes: 3

Paul
Paul

Reputation: 141917

There is nothing wrong with your if statement. The problem is that you're executing both these lines:

DONOTHING="$(printf 'good' > $RESULTFILE)"
SENDMAIL="$(printf 'bad' > $RESULTFILE)"

First writing good to the file and then overwriting it with bad. I think you meant to not execute the content of those lines, until later in your script:

DONOTHING="printf 'good' > $RESULTFILE"
SENDMAIL="printf 'bad' > $RESULTFILE"

It seems very weird to me to use variables to store code like that though. It will work, but why don't you just do this instead:

#!/bin/bash
WATCHDIR="/mnt/remote/ian/test"
OKTIME="7200"
RESULTFILE="/mnt/remote/ian/result.tmp"
ELAPSEDTIME="$(expr $(date +%s) - $(stat -c %Y $WATCHDIR))"

if [ "$ELAPSEDTIME" -ge "$OKTIME" ]; then
     printf 'bad' > "$RESULTFILE"
else
     printf 'good' > "$RESULTFILE"
fi

Upvotes: 0

Related Questions