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!
cmpto compare files../${1} > tmpshould result in runningans.txtas a command - don't you get "permission denied" or other error on that line?sh- what is your implementation ofsh? Does the problem persist when running underbash?cmpis better thandiffwhen you only want to know if files are different, but don't care about generating a patch to transform one file to the other.cmp -sexists so you don't need to redirect stdout and stderr at all;if cmp -s file1 file2; then echo "Files are identical"; else echo "Files are different"; fi/bin/shand/bin/bashbehave differently even if they're both provided by bash (but it's on systems where/bin/shis provided byash,dash, etc. that the differences get really big). If you're using bash-only syntax, always use#!/bin/bashor#!/usr/bin/env bash, not#!/bin/sh.