Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top