How do I suppress error messages from cp?

To suppress error output in bash, append 2>/dev/null to the end of your command. This redirects filehandle 2 (STDERR) to /dev/null. There are similar constructs in other shells, though the specific construct may vary slightly.


Redirect the error message (STDERR) to /dev/null:

root@ubuntu:~$ cp /srv/ftp/201*/wha*/*.jj ~/. 2>/dev/null

Example:

$ cp /srv/ftp/201*/wha*/*.jj ~/.  ##Error message gets printed
cp: cannot stat ‘/srv/ftp/201*/wha*/*.jj’: No such file or directory

$ cp /srv/ftp/201*/wha*/*.jj ~/. 2>/dev/null  ##No error message gets printed

Your question is not clear. The most sensible thing to do would be to not run cp at all when the wildcard doesn't match any file, rather than run cp and hide the error message.

To do that, if the shell is bash, set the nullglob option so that the wildcard pattern expands to nothing if it doesn't match any files. Then check whether the pattern expanded to anything, and don't call cp in that case.

#!/bin/bash
shopt -s nullglob
files=(/srv/ftp/201*/wha*/*.jj)
if [[ ${#files[@]} -ne 0 ]]; then
  cp "${files[@]}" ~
fi

In plain sh, test whether the glob was left unchanged, pointing to a non-existent file.

set -- /srv/ftp/201*/wha*/*.jj
if ! [ -e "$1" ] && ! [ -L "$1" ]; then
  cp "$@" ~
fi