How to ignore output of diff in bash

1.2k Views Asked by At

I tried to compare two files and output customized string. Following is my script.

#!/bin/bash

./${1} > tmp

if ! diff -q tmp ans.txt &>/dev/null; then
    >&2 echo "different"
else
    >&2 echo "same"
fi

When I execute script, I get:

sh cmp.sh ans.txt
different
Files tmp and ans.txt differ

The weird part is when I type diff -q tmp ans.txt &>/dev/null. No output will show up.

How to fix it(I don't want line:"Files tmp and ans.txt differ")? Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

Most probably the version of sh you are using doesn't understand the bash (deprecated/obsolete) extension &> that redirect both stdout and stderr at the same time. In posix shell the command &>/dev/null I think is parsed as { command & }; > /dev/null - it results in running the command in the background & and the > /dev/null part I think is ignored, as it just redirect output of a nonexistent command - it's valid syntax, but executes nothing. Because running the command in the background succeeds, the if always succeeds.

Prefer not to use &> - use >/dev/null 2>&1 instead. Use diff to pretty print the files comparison. Use cmp in batch scripts to compare files.

if cmp -s tmp ans.txt; then