Comparison function that compares two text files in Unix

前端 未结 5 2064
走了就别回头了
走了就别回头了 2021-02-07 12:54

I was wondering if anyone could tell me if there is a function available in unix, bash that compares all of the lines of the files. If they are different it should output true/f

5条回答
  •  无人共我
    2021-02-07 13:23

    There are several ways to do this:

    • cmp -s file1 file2: Look at the value of $?. Zero if both files match or non-zero otherwise.
    • diff file1 file2 > /dev/null: Some forms of the diff command can take a parameter that tells it not to output anything. However, most don't. After all, you use diff to see the differences between two files. Again, the exit code (you can check the value of $? will be 0 if the files match and non-zero otherwise.

    You can use these command in a shell if statement:

    if cmp -s file1 file2
    then
       echo "The files match"
    else
       echo "The files are different"
    fi
    

    The diff command is made specifically for text files. The cmp command should work with all binary files too.

提交回复
热议问题