开发者

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

开发者 https://www.devze.com 2023-02-16 07:25 出处:网络
I have a shell script that I\'m working on with this line of code that d开发者_如何学运维oes a loop through local files (.gz) and does an scp. I want to test for a failed scp if possible. I am doing a

I have a shell script that I'm working on with this line of code that d开发者_如何学运维oes 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


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.


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


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消