Getting Error count

Hi All,

I have the below code. After doing copy and move if there is an error that should be initially captured as 1 and incremented for each error with exiting. Finally if the total error count to be greater than 2 then I need to exit the script.

########################

cp a/x.csv b/x.csv
if [ $? -ne 0 ]; then
count it as 1

cp a/d.csv b/f.csv

if [ $? -ne 0 ]; then
count it as 2( Incrementing the error count)

mv b/x.csv b/vin.csv
if [ $? -ne 0 ]; then
count it as 3( Incrementing the error count)

mv b/f.csv b/test.csv
if [ $? -ne 0 ]; then
count it as 3( Incrementing the error count)

If total error count is greater than 2 then 
Exit 1

Please let me know how to acheive this.

Thanks.

#!/bin/bash

COUNT=0

cp a/x.csv b/x.csv 2>/dev/null
(( $? != 0 )) && (( COUNT++ ))

cp a/d.csv b/f.csv 2>/dev/null
(( $? != 0 )) && (( COUNT++ ))

mv b/x.csv b/vin.csv 2>/dev/null
(( $? != 0 )) && (( COUNT++ ))

mv b/f.csv b/test.csv 2>/dev/null
(( $? != 0 )) && (( COUNT++ ))

(( COUNT > 2 )) && exit 1

exit 0
1 Like

What shell are you using? What OS are you using?

Your pseudo-code raise lots of ambiguities. You have if s and then s, but no else s or fi s.

count it as digit is not a valid shell command and doesn't seem to match the comments before your pseudo-code.

If you are using any POSIX conforming shell (such as ksh or bash ), you could also try this alternative to what fpmurchpy suggested:

count=0
cp a/x.csv b/x.csv || count=$((count + 1))
cp a/d.csv b/f.csv || count=$((count + 1))
mv b/x.csv b/vin.csv || count=$((count + 1))
mv b/f.csv b/test.csv || count=$((count + 1))
exit $((count > 2))

As shown by fpmurphy, some of the arithmetic could be further simplified with a 1993 or later version of ksh or a recent version of bash . This code won't hide the diagnostics if some of the commands fail. (The code fpmurphy suggested will hide any diagnostics.)

It seems very strange to me to try to perform either of those mv commands if the corresponding cp command preceding it failed. It also seems very strange to return a 0 exit code if one or two of the cp or mv commands fails. But this code seems to do what you asked for.

1 Like