Bash Shell 脚本:使用 Diff 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21413406/
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-10 00:38:48  来源:igfitidea点击:

Bash Shell Script: Using Diff command

bashshelldiff

提问by Gabriel

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 ']'

teste.sh: [: 缺少 ']'

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.

我正在尝试使用 diff 找出这两个文件中文本的差异。

回答by Raman Shah

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.

除了区分未定义的变量 $names 和 $names2 而不是您创建的文件(names.lst 和 names2.lst)之外,还有一些语法错误:您需要在方括号周围留一个空格来执行条件。

#! /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

回答by F. Hauri

There is some little errors...

有一些小错误...

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

  2. variables $nameand $name2seem not populated.

  1. teste.sh: [: missing ']': 你错过了一个空格 0

  2. 变量$name$name2似乎没有填充。

And some improvement could be:

一些改进可能是:

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

但是在最近的 bash 下执行此操作不需要编写脚本:

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 properlyand 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