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!
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 thecommand &>/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, theif
always succeeds.Prefer not to use
&>
- use>/dev/null 2>&1
instead. Usediff
to pretty print the files comparison. Usecmp
in batch scripts to compare files.