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
shyou 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/nullI think is parsed as{ command & }; > /dev/null- it results in running the command in the background&and the> /dev/nullpart 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, theifalways succeeds.Prefer not to use
&>- use>/dev/null 2>&1instead. Usediffto pretty print the files comparison. Usecmpin batch scripts to compare files.