Trapping the error during copy

I have a requirement:

During copy command for example:

cp -rf <sourceDir> <destinationDir>

this command may fails for many reasons like:

  1. source or destination directory does not exist
  2. destination directory does not have sufficient space
  3. directories are not mounted
    ... Or may be any other reasons which are not in my head.

The problem is during scripting when we copy with -r (recursive option) then if any error occurs it got reported to the user recursively for all the files in the directory.

So if we use to dump these errors {I mean not to be shown to the user} we can very well do with:

2>/dev/null

But my problem is I want this error to be reported only once to the user, NOT repeatedly (i.e. not recursively n times)

Thanks in Advance.
Ambar

You can catch the error code at the end with something like:

cp -rf <sourceDir> <destinationDir> 2> /dev/null
RC=$?

if [[ $RC -ne 0 ]]; then
     echo "Hey, something went wrong!"
fi

If you want the errors in some file to check them later, you just redirect STDERR to a file instead of /dev/null.

Thanks Zaxxon for the response.

Yes, we can trap the error and show the message to the user based on the return code.

But I wanted the message which can tell user why it is failed and only once. If we give error message to the user that "Something went wrong" that way user have no idea what went wrong.

Since the error message reported from OS have correct reason like :

cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libclntshcore.so.12.1': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libhasgen12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libnnz12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libasmclntsh12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libclntsh.so.12.1': No space left on device

but is repeated for all the rest of the files. I wanted the message like :

echo "Process Failed \n"
echo "Reason:"
echo "No space left on device"

I added some "permission denied"... something like this?

$ cat infile
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libclntshcore.so.12.1': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libhasgen12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libhasgen123456789.so': Permission denied
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libnnz12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libasmclntsh12.so': No space left on device
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libasmclntsh123456789.so': Permission denied
cp: writing `/testX/file2016-08-11_07-03-10AM/ext/lib/libclntsh.so.12.1': No space left on device
$ awk -F "': " '{print $NF}' infile | sort -u
No space left on device
Permission denied
1 Like