laker02
laker02

Reputation: 117

Diff command in bash

Every time i run the following bash command, i get an error:

Here's the code:

sort -b ./tests/out/$scenario > $studentFile
sort -b ./tests/out/$scenario > $profFile
$(diff $studentFile $profFile)
  if [ $? -eq 0 ]
      then 
          echo "Files are equal!"
      else
          echo "Files are different!"
      fi

Here's the error:

./test.sh: 2c2: not found

I basically want to sort two files, and then check if they are equal or not. What i don't understand is what this error means and how i can get rid of it. Any help will be greatly appreciated.

Thanks!

Upvotes: 1

Views: 27584

Answers (2)

pasaba por aqui
pasaba por aqui

Reputation: 3539

Short answer: use

diff $studentFile $profFile

instead of:

$(diff $studentFile $profFile)

Long answer:

diff $studentFile $profFile 

will provide an output of several lines, first one, in your example, is "2c2". If you enclose the diff command in $(), the result of this expression is an string with the concatenation of all the lines, "2c2 ...". In your script, this result is executed by bash as new command, with the result of "command not found: 2c2".

Compare, by example:

$(diff $studentFile $profFile)

and:

echo $(diff $studentFile $profFile)

*** Addendum ***

if diff $studentFile $profFile > /dev/null 2>&1
then
  echo "equal files"
else
  echo "different files"
fi

is a possible way of reach the expected result.

Upvotes: 7

Kusalananda
Kusalananda

Reputation: 15633

Your command

$(diff $studentFile $profFile)

executes the result of running the diff command on the two files. The 2c2 that your shell complains about is probably the first word in the output from diff.

I'm assuming that you simply want to see the output from diff:

diff $studentFile $profFile

If you want to compare the file for equality in a script, consider using cmp:

if cmp -s $studentFile $profFile; then
    # Handle file that are equal
else
    # Handle files that are different
fi

The diff utility is for inspecting differences between files, while cmp is much better suited for just simply testing if files are different (in a script, for example).

For more specialized cases there is the comm utility that compares lines in sorted files.

Upvotes: 2

Related Questions