0

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
SteveHu
  • 82
  • 9

1 Answers1

0

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?

qmeeus
  • 2,341
  • 2
  • 12
  • 21
  • Even more surprisingly, one gets `[ is a shell builtin`, but `[[ is a shell keyword`. The former is perhaps a “legacy” matter related to `/usr/bin/[` and standard POSIX shells whereas the latter is closer to what this construct “should be” in Bash. – Andrej Podzimek Oct 13 '22 at 11:09
  • Please don't answer simple typo questions. Just leave a comment and vote to close. – tripleee Oct 13 '22 at 11:09
  • @tripleee, in my opinion, this is not a typo, this comes from misunderstanding what brackets are in shell. And that means that an explanation is worth the trouble... – qmeeus Oct 13 '22 at 11:22
  • Yeah, but we already have a canonical for that, so please vote to close as a duplicate. The [`bash` tag info page](/tags/bash/info) has a list of common FAQs. – tripleee Oct 13 '22 at 11:23
  • That being said, I see that this question is a duplicate, which is a good argument for closing – qmeeus Oct 13 '22 at 11:24