entonio
entonio

Reputation: 2173

Compare multiline strings in bash variables

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?

Upvotes: 12

Views: 10826

Answers (3)

dimo414
dimo414

Reputation: 48864

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.

Upvotes: 7

Édouard Lopez
Édouard Lopez

Reputation: 43401

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"
}

Upvotes: 4

Michael Vehrs
Michael Vehrs

Reputation: 3363

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

Upvotes: 6

Related Questions