Mihai Paul
Mihai Paul

Reputation: 41

Failing to redirect error message in my command

I'm a rookie in bash scripting, and here's basically my bash script:

Z=`diff -Z $ref_out $exec_out | grep "[<>]" | wc -l` 2>/dev/null
if [ $Z -gt 0 ]; then
echo "*** testcase: [ stdout - FAILED ]"
else
echo "*** testcase: [ stdout - PASSED ]"
fi

I would like to suppress the error message from diff such as:

diff: No such file or directory

This could either result from no $ref_out or $exec_out file, though I'm redirecting to /dev/null, this error message still shows up. Any help?

Upvotes: 2

Views: 372

Answers (2)

codeforester
codeforester

Reputation: 42999

Your redirection isn't working because it is being applied to the parent shell, not the subshell that runs the pipeline.

If you want to send the stderr of a bunch of commands to /dev/null, you could do it this way - I am using $() instead of backticks:

Z=$( { diff -Z $ref_out $exec_out | grep "[<>]" | wc -l; } 2>/dev/null )

Here, 2>/dev/null applies to all the commands inside { }.


There are many issues in your code. You could rewrite it in a better way:

if diff -Z "$ref_out" "$exec_out" 2>/dev/null | grep -q "[<>]"; then
  echo "*** testcase: [ stdout - FAILED ]"
else
  echo "*** testcase: [ stdout - PASSED ]"
fi
  • grep -q is a better way to do this check and you won't need a wc -l unless you want to know the exact number of matches
  • you need to quote your variables
  • if statement can include commands; you don't need to capture the output in order to use it in the if statement

You can use shellcheck to validate your shell script and see if you are making the usual mistakes that can break your code.

Upvotes: 0

SteveK
SteveK

Reputation: 995

You need diff's stderr to go to /dev/null, so it should instead be:

Z=`diff -Z $ref_out $exec_out 2> /dev/null | grep "[<>]" | wc -l`

Upvotes: 3

Related Questions