1

Can anyone help me out to figuring what is wrong with this program?

#!/bin/bash

find teste1 > names.lst
find teste2 > names2.lst

result=$(diff -y -W 72 $names $names2)

if [ $? -eq 0]; then
echo "files are the same"
else
echo "files are different"
echo "$result"
fi

It returns the following errors:

diff: missing operand

teste.sh: [: missing ']'

Files are different

(a blank space appears here)

The blank space is the variable "result" but why did it not save the differences between the 2 files?

I am trying to use diff to find out the differences in the texts on both those files.

2
  • 1
    Where did you populate the variables $names, $names2? I assume those are intended to be names.lst, names2.lst but this code does not set the variables. Commented Jan 28, 2014 at 18:13
  • @MichaelBerkowski: Ah, I guess that explains why it isn't quite working then :/ I changed and declared those variables with the value of the names.lst and names2.lst THANKS! :D Commented Jan 28, 2014 at 18:15

2 Answers 2

5

In addition to diffing undefined variables $names and $names2 instead of the files you created (names.lst and names2.lst), there is a couple of syntax error: you need a space around square brackets to execute the conditional.

#! /bin/bash

find teste1 > names.lst
find teste1 > names2.lst

result=$(diff -y -W 72 names.lst names2.lst)

if [ $? -eq 0 ]
then
        echo "files are the same"
else
        echo "files are different"
        echo "$result"
fi
Sign up to request clarification or add additional context in comments.

Comments

2

There is some little errors...

  1. teste.sh: [: missing ']' : you miss a space after 0

  2. variables $name and $name2 seem not populated.

And some improvement could be:

But doing this under recent bash don't require to write a script:

result="$(diff -y <(find teste1) <(find teste2))" &&
   echo files are the same ||
   { echo files differ; echo $result; }

or

result="$(diff -y <(find teste1) <(find teste2))" &&
   echo files are the same || printf "files differ:\n%s" "$result"

One of the main advantage of this is that there is no need of temporary files.

Of course this could be written properly and more readable:

#!/bin/bash

files=(
    "/path1/teste 1"
    "/path2/teste 2"
)

if result="$(
    diff -y -W78 <(
        find ${files[0]}
      ) <(
        find ${files[1]}
      ) )" 
  then
    echo "Files are the sames"
  else
    echo "Files are differents"
    echo "$result"
  fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.