I have a script with two multiline strings. I'd like to know if they are equal. I haven't found a way to do this, because while comparing is easy, passing the value of the variables to the comparison thingamajig isn't. I haven't had success piping it to diff, but it could be my ineptitude (many of the things I've tried resulted in 'File name too long' errors). A workaround would be to replace newlines by some rare character, but it meets much the same problem. Any ideas?
This might be helpful:
var=$(echo -e "this\nis \na\nstring" | md5sum)
var2=$(echo -e "this\nis not\na\nstring" | md5sum)
if [[ $var == $var2 ]] ; then echo true; else echo false; fi
                        Even if you're using sh you absolutely can compare multiline strings. In particular there's no need to hash the strings with md5sum or another similar mechanism.
Demo:
$ cat /tmp/multiline.sh
#!/bin/sh
foo='this
is
a
string'
bar='this
is not
the same
string'
    
[ "$foo" = "$foo" ]  && echo SUCCESS || echo FAILURE
[ "$foo" != "$bar" ] && echo SUCCESS || echo FAILURE
$ /tmp/multiline.sh
SUCCESS
SUCCESS
In bash you can (and generally should) use [[ ... ]] instead of [ ... ], but they both still support multiline strings.
Working with bats and bats-assert I sued the solution from @dimo414 (upvote his answer)
@test "craft a word object" {
  touch "$JSON_FILE"
  entry=$(cat <<-MOT
  {
    "key": "bonjour",
    "label": "bonjour",
    "video": "video/bonjour.webm"
  },
MOT
)
  run add_word "bonjour"
  content=$(cat $JSON_FILE)
  assert_equal "$entry" "$content"
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With