how to output success or failure of cp command to file

user2841861 picture user2841861 · Nov 6, 2013 · Viewed 17.7k times · Source

I'm going to be running a shell script containing a CP command using a scheduled cron job. I would like to include in the script something to output to a log file whether the copy was successful or failed.

Appreciate any advice in advance.

Thanks

Answer

SBI picture SBI · Nov 6, 2013

You can check the return code of cp. From the cp man page:

EXIT STATUS
    The cp utility exits 0 on success, and >0 if an error occurs.

The exit code of the last operation is stored in the special variable $?, so you can do something like this:

cp .. ..
echo $? >> outputfile

Most likely, you'll want to have some sort of "custom" error message. For that purpose, you can check the value of $?

cp .. ..
if [ $? -ne 0 ]
then
    echo "there was an error" >> outputfile
fi

I hope that gets you started.