Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare multiline strings in bash variables

Tags:

string

bash

pipe

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?

like image 680
entonio Avatar asked May 30 '16 10:05

entonio


3 Answers

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
like image 166
Michael Vehrs Avatar answered Oct 12 '22 07:10

Michael Vehrs


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.

like image 5
dimo414 Avatar answered Oct 12 '22 07:10

dimo414


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"
}
like image 4
Édouard Lopez Avatar answered Oct 12 '22 05:10

Édouard Lopez