capturing exceptions from an scp clause

hpunix

I have a script, that will scp -p a file. The server has keys set up. So I don't even pass a username.

scp -p filename server:/directory

There is a small chance that I can get an error. could be networking, etc... this is run from a job. I like to capture all exceptions when I do this.

I can do
if { $? - eq 1 ]; then Log a message.

how would I capture the exception in a scp clause?

You don't need to use $? when checking a command's return value. You can check the command directly.

if ! scp source destination
then
        echo "something bad happened" >&2
fi

Or even

scp source destination || echo "something bad happened" >&2

If anything goes wrong, it will likely print an error to standard error. If you redirect standard error into a logfile yourself before you run it, all error messages will go into it.

exec 2>path/to/logfile

touch / # Since you're not root, this should print 'permission denied' into logfile