bash 中的 Diff 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30559296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:05:57  来源:igfitidea点击:

Diff command in bash

bashdiff

提问by laker02

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

每次运行以下 bash 命令时,都会出现错误:

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!

谢谢!

回答by pasaba por aqui

Short answer: use

简短回答:使用

diff $studentFile $profFile

instead of:

代替:

$(diff $studentFile $profFile)

long answer:

长答案:

diff $studentFile $profFile 

wil 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 "2c2 ...". This result is now taken by bash as new command, with the result of "command not found: 2c2".

将提供多行的输出,在您的示例中,第一行是“2c2”。如果将 diff 命令包含在 $() 中,则此表达式的结果为“2c2 ...”。这个结果现在被 bash 当作新命令,结果是“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

回答by Kusalananda

Your command

你的命令

$(diff $studentFile $profFile)

executes the resultof running the diffcommand on the two files. The 2c2that your shell complains about is probably the first word in the output from diff.

执行对两个文件运行命令的结果diff。在2c2你的shell抱怨可能是从输出的第一个字diff

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

我假设您只想查看以下输出diff

diff $studentFile $profFile

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

如果要在脚本中比较文件的相等性,请考虑使用cmp

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

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

diff实用程序用于检查文件之间的差异,而cmp更适合仅测试文件是否不同(例如,在脚本中)。

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

对于更特殊的情况,有comm比较排序文件中的行的实用程序。