Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash string comparasion does not work as expected

I use this bash code to test whether two strings are equal, but the result is not as what I exptect. I have used "" to wrap two strings and used [[]] rather than [] in if condition, but still failed. Where did I do wrong? Thanks in advance.

#!/bin/bash
touch a.txt b.txt
date -r a.txt +%y-%m-%d > b.txt
A="$(cat b.txt)"
B="$(date -r a.txt +%y-%m-%d)"
if [["$A" == "$B"]]
then
  echo "equal"
else
  echo "not equal"
fi

Error is listed below.

➜  ~ chmod a+x test.sh
➜  ~ ./test.sh
./test.sh: line 6: [[22-10-13: command not found
not equal

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to put a space between [[ and "$A" and between "$B" and ]].

This is because in bash, [, ], [[ and ]] are commands:

$ type [
[ is a builtin

Weird right?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading