Antonín Kříž Antonín Kříž - 10 days ago 5
Linux Question

Bash - comparing output of two commands

I have this code:

#!/bin/bash

CMDA=$(curl -sI website.com/example.txt | grep Content-Length)

CMDB=$(curl -sI website.com/example.txt | grep Content-Length)

if [ "CMDA" == "CMDB" ];then
echo "equal";
else
echo "not equal";
fi


with this output

root@abcd:/var/www/html# bash ayy.sh
not equal


which should be "equal" instead of "not equal". What did I do wrong?

Thnaks

Answer

You forgot the $ for the variables CMDA and CMDB there. This is what you need:

if [ "$CMDA" = "$CMDB" ]; then

I also changed the == operator to =, because man test only mentions =, and not ==.

Also, you have some redundant semicolons. The whole thing a bit cleaner:

if [ "$CMDA" = "$CMDB" ]; then
  echo "equal"
else
  echo "not equal"
fi
Comments