Check if command error contains a substring

I'd do it like this

# Make sure we always get error messages in the same language
# regardless of what the user has specified.
export LC_ALL=C

case $(cp file1 file2 2>&1) in 
    #or use backticks; double quoting the case argument is not necessary
    #but you can do it if you wish
    #(it won't get split or glob-expanded in either case)
    *"No such file"*)
        echo >&2 "File does not exist. Please check your files and try again." 
        ;;
    *"omitting directory"*)
        echo >&2 "You have specified a directory instead of a file"
        ;;
esac

This'll work with any POSIX shell too, which might come in handy if you ever decide to convert your bash scripts to POSIX shell (dash is quite a bit faster than bash).

You need the first 2>&1 redirection because executables normally output information not primarily meant for further machine processing to stderr. You should use the >&2 redirections with the echos because what you're ouputting there fits into that category.

Tags:

Bash