14

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

user2841861
  • 423
  • 2
  • 8
  • 22

1 Answers1

33

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.

SBI
  • 2,322
  • 1
  • 17
  • 17
  • When I try this the output I get is..-bash: 0: command not found – user2841861 Nov 06 '13 at 11:43
  • That works. Thank you. If i wanted a customized message something other than 0 written to the log file what would I need to do? Thanks in advance. – user2841861 Nov 06 '13 at 11:50
  • Well, instead of just printing the exit code to the file, check it first with if. – SBI Nov 06 '13 at 11:52
  • sorry I'm really new to this. Would that be something like if [$? -eq 0]; echo 'copied success' >> my_file.txt. I get a syntax error: unexpected end of file from this. – user2841861 Nov 06 '13 at 11:59
  • I can't seem to get this working. rm -rf ../feeds/SetupID_162/TODAY/TODAY/* if [ $? -ne 0 ] then echo "copied success" >> my_file fi I get the error Macquarie.sh: line 5: syntax error near unexpected token `fi' Macquarie.sh: line 5: `fi' – user2841861 Nov 06 '13 at 12:34
  • Post your entire file on pastebin or something similar. (rep too low for chat, so abusing the comments for once). – SBI Nov 06 '13 at 17:20