N
N
Nikita Maksimov2020-09-10 14:34:49
bash
Nikita Maksimov, 2020-09-10 14:34:49

Why does the comparison always return true when comparing two strings in bash?

Friends, hello everyone!

I’ll write right away that I’m not strong in writing bash scripts, but such a need arose.

I am attaching a simple example:

# !/bin/sh
res=$(curl -Isk https://........./api/rest.php | head -n 1 | sed 's/\r//g')
res_string="HTTP/1.1 200 OK"
if [ "$res"="$res_string" ]
then
service nginx status && service httpd status
else
echo "CANSEL"
fi


The problem is that when executed, the check always returns true, even if the check string is changed.
I broke my head, but I just can not understand the reason for this behavior.

Tell me where to dig.

UPD:
When testing with bash -x I get the following output:
bash -x script.sh 
++ curl -Isk https://...../api/rest.php
++ head -n 1
++ sed 's/\r//g'
+ res='HTTP/1.1 200 OK'
+ res_string='HTTP/1.1 200 OK'
+ '[' 'HTTP/1.1 200 OK=HTTP/1.1 200 OK' ']'
+ service nginx status
nginx (pid  17277) is running...
+ service httpd status
httpd (pid  17321) is running...


If res_string is changed to any value, then it will still be true.
For clarity:
bash -x script.sh 
++ curl -Isk https://......./api/rest.php
++ head -n 1
++ sed 's/\r//g'
+ res='HTTP/1.1 200 OK'
+ res_string='38942983478239423олвыалодлаывдHTTP/1.1 200 OK'
+ '[' 'HTTP/1.1 200 OK=38942983478239423олвыалодлаывдHTTP/1.1 200 OK' ']'
+ service nginx status
nginx (pid  17277) is running...
+ service httpd status
httpd (pid  17321) is running...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kocherman, 2020-09-10
@mknk

because there [ "$res" = "$res_string" ]are spaces between the space
The space is not put only when assigning a value to a variable
For example,res=123

S
Saboteur, 2020-09-11
@saboteur_kiev

#!/bin/sh
res=$(curl -lsk -o /dev/ev/null -w "%{http_code}" https://........./api/rest.php)
if [ "$res" = "200" ]; then
  service nginx status && service httpd status
else
  echo "CANCEL"
fi

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question