jdamae
jdamae

Reputation: 3909

best way to programmatically check for a failed scp in a shell script

I have a shell script that I'm working on with this line of code that does a loop through local files (.gz) and does an scp. I want to test for a failed scp if possible. I am doing a loop so I can echo each file name to a log so I can keep track of it.

Can someone show me how to check for failed scp? or better yet, a good code example to do this? Thanks for your help.

for gzfile in $LOCALDMPDIR/*.gz
do
  /usr/bin/scp -P 2222 -i $KEYFILE $gzfile foobar@$1:$TGTDIR
  echo "$gzfile is done. " 2>&1
done

Upvotes: 21

Views: 41264

Answers (5)

4givN
4givN

Reputation: 3234

use :

if [ $? -eq 0 ];
then
    echo "OK"</br>
else
    echo "NOK"</br>
fi

there're blank after "[" and before "]". don't surround $? and 0 with quotes

Upvotes: 18

Cole Tierney
Cole Tierney

Reputation: 10314

You could also try to capture the error to a log:

for gzfile in $LOCALDMPDIR/*.gz
do
  /usr/bin/scp -P 2222 -i $KEYFILE $gzfile foobar@$1:$TGTDIR 2>>/var/log/scperror.log \
  && echo "$gzfile is done." \
  || echo "scp error: $gzfile"
done

Upvotes: 1

Engineiro
Engineiro

Reputation: 1146

For the simpleminded like me out there who spent longer than normal messing with formatting errors:

scp "fromHere" hostname:"toThere"
if [ "$?" -eq "0" ];
then
    echo "SUCCESS"
else
    echo "FAIL"
fi

Upvotes: 0

Brent Worden
Brent Worden

Reputation: 10974

Use $? to access the return value of the last command. Check the man page for scp to verify, but I think a return value of zero means success. A non-zero value means some kind of failure.

Upvotes: 26

Morten Kristensen
Morten Kristensen

Reputation: 7613

You can check the varaible $? to see the return code of scp. If it returns non-zero then an error occurred.

Upvotes: 4

Related Questions