简体   繁体   English

Bash Shell脚本:使用Diff命令

[英]Bash Shell Script: Using Diff command

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来找出这两个文件的文字差异。

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

There is some little errors... 有一些小错误...

  1. teste.sh: [: missing ']' : you miss a space after 0 teste.sh: [: missing ']' :您在0后错过了一个空格

  2. variables $name and $name2 seem not populated. 变量$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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM