Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output success or failure of cp command to file

Tags:

output

cp

logfile

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

like image 603
user2841861 Avatar asked Nov 06 '13 11:11

user2841861


People also ask

How do you write the output of a command to a file?

Right-click the top result and select the Run as administrator option. Type the following command to save the output to a text file and press Enter: YOUR-COMMAND | Out-File -FilePath C:\PATH\TO\FOLDER\OUTPUT. txt.

What is the output of cp?

To view output when files are copied, use the -v (verbose) option. By default, cp will overwrite files without asking. If the destination file name already exists, its data is destroyed. If you want to be prompted for confirmation before files are overwritten, use the -i (interactive) option.

How do I know if my previous command was successful?

variable in Linux. “$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred.

How do you get help about the command cp in Linux?

cp command require at least two filenames in its arguments. Syntax: cp [OPTION] Source Destination cp [OPTION] Source Directory cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory First and second syntax is used to copy Source file to Destination file or Directory.


1 Answers

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.

like image 87
SBI Avatar answered Sep 19 '22 09:09

SBI