codec
codec

Reputation: 8796

bash string not matching in if clause

I am running into a strange issue. In the below piece of code the echo statement works fine and in success.txt I get b4 running=false with RUNNING:false which means $RUNNING = false.

But it is not going into the if block.

echo "b4 running=false with RUNNING:"$RUNNING >> /tmp/success.txt
if [[ $RUNNING == "false" ]]; then
  echo "in running=false" >> /tmp/success.txt    
  exit 2
fi

I also tried

if [[ $RUNNING == false ]]; then
  echo "in running=false" >> /tmp/success.txt    
  exit 2
fi

if [ "$RUNNING" == "false" ]; then
  echo "in running=false" >> /tmp/success.txt    
  exit 2
fi

if [ "$RUNNING" == false]; then
  echo "in running=false" >> /tmp/success.txt    
  exit 2
fi

if [ "$RUNNING" == "false" ]; then
  echo "in running=false" >> /tmp/success.txt    
  exit 2
fi

None of these is working. I am sure I am missing something very small here.

Upvotes: 0

Views: 90

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

When I try

RUNNING=false
if [[ $RUNNING == false ]]; then
    echo 1
fi

if [ "$RUNNING" == "false" ]; then
    echo 2
fi

if [ "$RUNNING" == false]; then
    echo 3
fi

if [ "$RUNNING" == "false" ]; then
    echo 4
fi

I get

1
2
/tmp/a.sh: line 10: [: missing `]'
4

Fixing the third one from

if [ "$RUNNING" == false]; then

to

if [ "$RUNNING" == false ]; then

Note the additional space between false and ]. Now I get

1
2
3
4

So all four are valid, if $RUNNING is false. The difference might be a trailing new line character or some white space around false/$RUNNING, if the value is captured from the output of some command.

See Conditional Constructs and Bash Conditional Expressions for more details.

Upvotes: 1

Forty2
Forty2

Reputation: 16

have you tried the following:

if [ $RUNNING == "false" ]; then
    echo "test"
fi

That seems to work for me.

Cheers

Upvotes: 0

Related Questions